【LeetCode】 036. Valid Sudoku

来源:互联网 发布:淘宝靠谱ipad二手店铺 编辑:程序博客网 时间:2024/06/03 03:32

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

public class Solution {    public boolean isValidSudoku(char[][] board) {        HashSet<Character> hs = new HashSet<Character>();        for (int i = 0; i < 9; i++) {            for (int j = 0; j < 9; j++) {                if (board[i][j] == '.') {                    continue;                }                if (hs.contains(board[i][j])) {                    return false;                }                hs.add(board[i][j]);            }            hs.clear();        }        for (int j = 0; j < 9; j++) {            for (int i = 0; i < 9; i++) {                if (board[i][j] == '.') {                    continue;                }                if (hs.contains(board[i][j])) {                    return false;                }                hs.add(board[i][j]);            }            hs.clear();        }        for (int row = 0; row < 3; row++) {            for (int col = 0; col < 3; col++) {                int temp1 = row * 3;                int temp2 = col * 3;                for (int i = temp1; i < temp1 + 3; i++) {                    for (int j = temp2; j < temp2 + 3; j++) {                        if (board[i][j] == '.') {                            continue;                        }                        if (hs.contains(board[i][j])) {                            return false;                        }                        hs.add(board[i][j]);                    }                }                hs.clear();            }        }        return true;    }}


0 0
原创粉丝点击