Valid Sudoku

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.

rules:

1. 同一行中1-9出现次数不重复

2. 同一列中1-9出现次数不重复

3. 9宫格中1-9出现次数不重复

 

九宫格 block的顺序 

0 1 2 

3 4 5 

6 7 8  

public boolean isValidSudoku(char[][] board){
            boolean [][] rows=new boolean[9][9];
            boolean [][] cols=new boolean[9][9];
            boolean [][] blocks=new boolean[9][9];
            for(int i=0;i<9;i++){
                for(int j=0;j<9;j++){
                    rows[i][j]=false;
                    cols[i][j]=false;
                    blocks[i][j]=false;
                }
            }
            for (int i = 0; i < 9; ++i) {  
                for (int j = 0; j < 9; ++j) {
                    int c = board[i][j] - '1';
                    if (board[i][j] == '.') continue;  
                    if (rows[i][c] || cols[j][c] || blocks[i - i % 3 + j / 3][c])  
                        return false;  
                    rows[i][c] = cols[j][c] = blocks[i - i % 3 + j / 3][c] = true;  
                }  
            }  
            return true;  
        }

 

posted @ 2014-02-06 01:30  Razer.Lu  阅读(167)  评论(0编辑  收藏  举报