【LeetCode】36

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.(http://sudoku.com.au/TheRules.aspx)

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.

Solution 1:

依次检查每行,每列,每个子九宫格是否出现重复元素,用具有key唯一属性的map记录是否出现。重难点在于表示检查第i个九宫格

观察行号规律:

第0个九宫格:000111222; 第1个九宫格:000111222; 第2个九宫格:000111222;

第3个九宫格:333444555; 第4个九宫格:333444555; 第5个九宫格:333444555;

第6个九宫格:666777888; 第7个九宫格:666777888; 第8个九宫格:666777888;

可见对于每三个九宫格行号增3;对于单个九宫格,每三个格点行号增1。

因此第i个九宫格的第j个格点的行号可表示为i/3*3+j/3

观察列号规律:

第0个九宫格:012012012; 第1个九宫格:345345345; 第2个九宫格:678678678;

第3个九宫格:012012012; 第4个九宫格:345345345; 第5个九宫格:678678678;

第6个九宫格:012012012; 第7个九宫格:345345345; 第8个九宫格:678678678;

可见对于下个九宫格列号增3,循环周期为3;对于单个九宫格,每个格点行号增1,周期也为3。

周期的数学表示就是取模运算mod。

因此第i个九宫格的第j个格点的列号可表示为i%3*3+j%3

 1 class Solution {
 2 public:
 3     bool isValidSudoku(vector<vector<char>>& board) {
 4          for(int i = 0; i < 9; i ++)
 5         {
 6             unordered_map<char, bool> row;   
 7             unordered_map<char, bool> column;   
 8             unordered_map<char, bool> bod;   
 9             for(int j = 0; j < 9; j ++)
10             {
11                 if(board[i][j] != '.')
12                 {
13                     if(row[board[i][j]] == true)    //若row[board[i][j]]不存在,返回0
14                         return false;
15                     row[board[i][j]] = true;
16                 }
17                 if(board[j][i] != '.')
18                 {
19                     if(column[board[j][i]] == true)
20                         return false;
21                     column[board[j][i]] = true;
22                 }
23                 if(board[i/3*3+j/3][i%3*3+j%3] != '.')
24                 {
25                     if(bod[board[i/3*3+j/3][i%3*3+j%3]] == true)
26                         return false;
27                     bod[board[i/3*3+j/3][i%3*3+j%3]] = true;
28                 }
29             }
30         }
31         return true;
32     }
33 };

Solution 2:在discussion上看到的屌屌的解法

 1 class Solution
 2 {
 3 public:
 4     bool isValidSudoku(vector<vector<char> > &board)
 5     {
 6         int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
 7 
 8         for(int i = 0; i < board.size(); ++ i)
 9             for(int j = 0; j < board[i].size(); ++ j)
10                 if(board[i][j] != '.')
11                 {
12                     int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
13                     if(used1[i][num] || used2[j][num] || used3[k][num])
14                         return false;
15                     used1[i][num] = used2[j][num] = used3[k][num] = 1;
16                 }
17 
18         return true;
19     }
20 };
原文地址:https://www.cnblogs.com/irun/p/4728800.html