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;
    }
}


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