美文网首页
36. Valid Sudoku

36. Valid Sudoku

作者: RobotBerry | 来源:发表于2017-05-04 11:15 被阅读0次

问题

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 '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

例子

A partially filled sudoku which is valid.

分析

数独的大小为9x9,可以分成9块,每一块大小为3x3。典型的数独如下图所示:

经典数独

数独的规则:

  • 每个横向和纵向行的数字不能重复,必须有且仅有1-9这9个数字;
  • 每块的数字不能重复,必须有且仅有1-9这9个数字。

题目要求验证数独的正确性,我们只需要对已有的数字验证上面两条规则就可以了。

要点

  • 理解数独的规则;
  • 使用unordered_set判断数字是否已经存在。

时间复杂度

O(n^2),n为数独的大小(长或宽),n一般来说是9

空间复杂度

O(n)

代码

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        for (int i = 0; i < 9; i++) {
            unordered_set<char> rs, cs;
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.' && rs.find(board[i][j]) != rs.end()) return false;
                else rs.insert(board[i][j]);
                if (board[j][i] != '.' && cs.find(board[j][i]) != cs.end()) return false;
                else cs.insert(board[j][i]);
            }
        }
        for (int i = 0; i < 9; i += 3) {
            for (int j = 0; j < 9; j += 3) {
                unordered_set<char> bs;
                for (int x = 0; x < 3; x++) {
                    for (int y = 0; y < 3; y++) {
                        if (board[i + x][j + y] != '.' && bs.find(board[i + x][j + y]) != bs.end()) return false;
                        else bs.insert(board[i + x][j + y]);
                    }
                }
            }
        }
        return true;
    }
};

相关文章

  • hash_table-special

    目录: 36、 Valid Sudoku 36. Valid Sudoku Determine if a Sudo...

  • Leetcode-36 有效的数独

    36. 有效的数独[https://leetcode-cn.com/problems/valid-sudoku/]...

  • 36. Valid Sudoku

    这一题按照三步走的策略,首先检查每一行是否有重复的,再检查每一列,最后检查每一块,都是按照字典去查找,代码如下: ...

  • 36. Valid Sudoku

    Determine if a 9x9 Sudoku board is valid. Only the filled...

  • 36. Valid Sudoku

    题目 Determine if a Sudoku is valid, according to: Sudoku P...

  • 36. Valid Sudoku

    这题的解法是brute force,复杂度是O(81 + 81)。。。判断每一行每一列的代码我的想法跟code g...

  • 36. Valid Sudoku

    问题 Determine if a Sudoku is valid, according to: Sudoku P...

  • 36. Valid Sudoku

    Determine if a Sudoku is valid, according to: Sudoku Puzz...

  • 36. Valid Sudoku

    问题描述 Determine if a Sudoku is valid, according to: Sudoku...

  • 36. Valid Sudoku

    题目链接 https://leetcode.com/problems/valid-sudoku/ 解题思路 直接看...

网友评论

      本文标题:36. Valid Sudoku

      本文链接:https://www.haomeiwen.com/subject/xxprtxtx.html