Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.


A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Example 2:

Input:
[
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being 
    modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9 and the character '.'.
  • The given board size is always 9x9.

 

 1 class Solution {
 2 public:
 3     bool isValidSudoku(vector<vector<char>>& board) {
 4         unordered_set<string> us;
 5         for(int i=0;i<board.size();++i)
 6             for(int j=0;j<board[i].size();++j)
 7             {
 8                 if('.'==board[i][j])continue;
 9                 string key="(";
10                 key+=board[i][j];
11                 key+=")";
12                 if(!us.insert(to_string(i)+key).second
13                   ||!us.insert(key+to_string(j)).second
14                   ||!us.insert(to_string(i/3)+key+to_string(j/3)).second)
15                     return false;
16             }
17         return true;
18     }
19 };

数独判断合法性.

数独的意思是9x9的二维数组, 每行,每列,每个3x3的小数组 都有9个数字,并且刚好是1-9, 顺序不关心.

一开始我还在想即使数组里面没有重复数字,是否有可能也不符合,看了答案压根没判断这个...看来是不用担心了

所以这题只需要判断数组里面是否符合上面描述的三个规则即可,把三个规则描述成三种格式的key,放入哈希set判断去重即可.

 

 

题外话, 9x9一共81个数字,理论上数字给的越少,答案越多,那么有没有可能给出N个数字时,即使没有数字违反上述规则也没有答案呢...

https://www.zhihu.com/question/30772895