Valid Sudoku 数独

Determine if a Sudoku is valid. The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

检测一个数独是否有效,数独的规则大家不明白的可以去百度一下。这里我们只需要检查当前的状态是否有效,而不用找到一个解。所以我们只要检查每行,每列以及没九个小方格内是否都没有重复数字出现就可以了。代码如下:
public class Solution {
    public boolean isValidSudoku(char[][] board) {
        HashSet<Character> set = new HashSet<Character>();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(set.contains(board[i][j])) 
                    return false;
                else if(board[i][j] != '.')
                    set.add(board[i][j]);
            }
            set.clear();
        }
        
        for(int i = 0; i < board[0].length; i++) {
            for(int j = 0; j < board.length; j++) {
                if(set.contains(board[j][i]))
                    return false;
                else if(board[j][i] != '.')
                    set.add(board[j][i]);
            }
            set.clear();
        }
        
        for(int m = 0; m < 3; m++) {
            for(int n = 0; n < 3; n++) {
                for(int i = 3 * m; i < 3 * m + 3; i++) {
                    for(int j = 3 * n; j < 3 * n + 3; j++) {
                        if(set.contains(board[i][j]))
                            return false;
                        else if(board[i][j] != '.')
                            set.add(board[i][j]);
                    }
                }
                set.clear();
            }
        }
        return true;
    }
}

你可能感兴趣的:(java,数独)