LeetCode 36.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.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

分析与解答:要求验证一个数独题目的合理性。由于涉及到反复地比较数字是否有重复,所以肯定要用到hashtable。然后就简单了,分别检查行、列、和九宫格即可。自己用unordered_map AC了一次,但其实不用也可以。毕竟只有81个数字。所以这里贴上一份别人的代码,比较简洁。

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



你可能感兴趣的:(table,hash)