LeetCode-Valid Sudoku

直接暴力的给每个需要检查的行 列 subbox建立一个hashset 检查是否有重复 记得要先判断一下这个位置是不是 '.'

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        for ( int i = 0; i < 9; i ++){ //
            HashSet<Character> set = new HashSet<Character> ();
            for ( int j = 0; j < 9; j ++) {
                if ( board[i][j] != '.'){
                    if ( set.contains(board[i][j]) ){
                        return false;
                    }
                    set.add(board[i][j]);
                }
            }
        }
        for ( int i = 0; i < 9; i ++){ //
            HashSet<Character> set = new HashSet<Character> ();
            for ( int j = 0; j < 9; j ++) {
                if ( board[j][i] != '.'){
                    if ( set.contains(board[j][i])){
                        return false;
                    }
                    set.add(board[j][i]);
                }
            }
        }
        for ( int box = 0; box < 9; box ++){ 
            HashSet<Character> set = new HashSet<Character> ();
            for ( int i = 0; i < 3; i ++ ){
                for ( int j = 0; j < 3; j ++ ){
                    int row = box / 3 * 3 + i;
                    int col = box % 3 * 3 + j;
                    if(  board[row][col] != '.'){
                        if ( set.contains( board[row][col]))
                            return false;
                        set.add( board[row][col]);
                    }
                }
            }
        }
        return true;
    }
}


你可能感兴趣的:(LeetCode-Valid Sudoku)