#leetcode#Valid Sudoku

参考了Code Ganker大神的思路, 


http://blog.csdn.net/linhuanmars/article/details/20748171


brute force, validate row by row, column by column,  then 9 sub-boxes of the grid.


public boolean isValidSudoku(char[][] board) {
    if(board==null || board.length!=9 || board[0].length!=9)
        return false;
    for(int i=0;i<9;i++)
    {
        boolean[] map = new boolean[9];
        for(int j=0;j<9;j++)
        {
            if(board[i][j] != '.')
            {
                if(map[(int)(board[i][j]-'1')])
                {
                    return false;
                }
                map[(int)(board[i][j]-'1')] = true;
            }
        }
    }
    for(int j=0;j<9;j++)
    {
        boolean[] map = new boolean[9];
        for(int i=0;i<9;i++)
        {
            if(board[i][j] != '.')
            {
                if(map[(int)(board[i][j]-'1')])
                {
                    return false;
                }
                map[(int)(board[i][j]-'1')] = true;
            }
        }
    }        
    for(int block=0;block<9;block++)
    {
        boolean[] map = new boolean[9];
        for(int i=block/3*3;i<block/3*3+3;i++)
        {
            for(int j=block%3*3;j<block%3*3+3;j++)
            {
                if(board[i][j] != '.')
                {
                   if(map[(int)(board[i][j]-'1')])
                   {
                      return false;
                   }
                   map[(int)(board[i][j]-'1')] = true;    
                }
            }
        }
    }
    return true;
}


对于这9个小方格的检验, 起初没看明白下面这段是怎么对应各个小方格的。

 for(int block=0;block<9;block++)
    {
        boolean[] map = new boolean[9];
        for(int i=block/3*3;i<block/3*3+3;i++)
        {
            for(int j=block%3*3;j<block%3*3+3;j++)
            {


block              1 2 3 4 5 6 7 8
i 0, 1, 2 0, 1, 2 0, 1, 2 3, 4, 5 3, 4, 5 3, 4, 5 6, 7, 8 6, 7, 8 6, 7, 8
j 0, 1, 2 3, 4, 5 6, 7, 8 0, 1, 2 3, 4, 5 6, 7, 8 0, 1, 2 3, 4, 5 6, 7, 8

上表中每一列下标组合成一个小方格


你可能感兴趣的:(LeetCode)