LeetCode:M-36. Valid Sudoku

Link


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.

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


数独规则 :

There are just 3 rules to Sudoku.

Each row must have the numbers 1-9 occuring just once.
Each column must have the numbers 1-9 occuring just once.
And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.


class Solution {
    public boolean isValidSudoku(char[][] board) {
        //注意数字是从1~9,所以数组长度9+1=10
        boolean[][] rowUsed = new boolean[9][10];//标记行中用过的数字
        boolean[][] columnUsed = new boolean[9][10];//标记列中用过的数字
        boolean[][] squareUsed = new boolean[9][10];//标记3*3方格中用过的数字
        
        for(int i=0; i<board.length; i++){
            for(int j=0; j<board[0].length; j++){
                if(board[i][j]!='.'){
                    int num = Integer.valueOf(board[i][j]+"");
                    int k = i/3*3+j/3;//k表示第几个3*3方格
                    if(rowUsed[i][num] || columnUsed[j][num] || squareUsed[k][num])
                        return false;
                    rowUsed[i][num] = columnUsed[j][num] = squareUsed[k][num] = true;
                }
            }
        }
        
        return true;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章