【leetcode-36】valid sudoku(java)

问题描述:
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 ‘.’.

分析:维护一个hash表,先按行查找,再按列查找,再按块查找。时间复杂度为O(n^2),n为输入的数组的行数。

代码如下:368ms

    public boolean isValidSudoku(char[][] board) {
        int row = board.length;
        int col = board[0].length;
        HashSet sets = new HashSet();
        for(int i = 0;ifor(int j = 0;jif(board[i][j]=='.')
                    continue;
                if(sets.contains(board[i][j]))
                    return false;
                if(board[i][j]>='1'&&board[i][j]<='9')
                    sets.add(board[i][j]);
                else
                    return false;
            }
        }
        for(int j = 0;jfor(int i = 0;iif(board[i][j]=='.')
                    continue;
                if(sets.contains(board[i][j]))
                    return false;
                if(board[i][j]>='1'&&board[i][j]<='9')
                    sets.add(board[i][j]);
                else
                    return false;
            }
        }
        int tmpRow,tmpCol;
        for(int i = 0;i3;i++){
            for(int j = 0;j3;j++){
                sets.clear();
                for(int k = 0;k<3;k++){
                    for(int m = 0;m<3;m++){
                        tmpRow = i*3+k;
                        tmpCol = j*3+m;
                        if(board[tmpRow][tmpCol]=='.')
                            continue;
                        if(sets.contains(board[tmpRow][tmpCol]))
                            return false;
                        if(board[tmpRow][tmpCol]>='1'&&board[tmpRow][tmpCol]<='9')
                            sets.add(board[tmpRow][tmpCol]);
                        else
                            return false;
                    }
                }
            }
        }
        return true;
    }

你可能感兴趣的:(leetcode)