蜗牛慢慢爬 LeetCode 36.Valid Sudoku [Difficulty: Medium]

题目

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.

翻译

数独嘛 略

Hints

Related Topics: Hash Table
通过哈希表实现O(n^2)的算法 即只遍历整个数独的表一遍就可以得到有效性判断

代码

C++

class Solution
{
public:
    bool isValidSudoku(vector<vector<char> > &board)
    {
        int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
        
        for(int i = 0; i < board.size(); ++ i)
            for(int j = 0; j < board[i].size(); ++ j)
                if(board[i][j] != '.')
                {
                    int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
                    if(used1[i][num] || used2[j][num] || used3[k][num])
                        return false;
                    used1[i][num] = used2[j][num] = used3[k][num] = 1;
                }
        
        return true;
    }
};

Java

//an interesting solution from discuss
public boolean isValidSudoku(char[][] board) {
    Set seen = new HashSet();
    for (int i=0; i<9; ++i) {
        for (int j=0; j<9; ++j) {
            char number = board[i][j];
            if (number != '.')
                if (!seen.add(number + " in row " + i) ||
                    !seen.add(number + " in column " + j) ||
                    !seen.add(number + " in block " + i/3 + "-" + j/3))
                    return false;
        }
    }
    return true;
}

Python

class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        row = {}
        col = {}
        cube = {}
        for i in range(0,9):
            row[i] = set()
            for j in range(0,9):
                if j not in col:    col[j] = set()
                if board[i][j] !='.':
                    num = int(board[i][j])
                    k = i/3*3+j/3
                    if k not in cube:   cube[k] = set()
                    if num in row[i] or num in col[j] or num in cube[k]: 
                        return False
                    row[i].add(num)
                    col[j].add(num)
                    cube[k].add(num)
        return True
        
posted @ 2017-08-31 11:45  cookielbsc  阅读(169)  评论(0编辑  收藏  举报