题目地址:Valid Sudoku
题目简介:
判断一个的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字1-9在每一行只能出现一次;
- 数字1-9在每一列只能出现一次;
- 数字1-9在每一个以粗实现分割的宫内只能出现一次;
上图是一个部分填充的有效的数独,数独部分空格内已填入了数字,空白格用'.'表示。
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.
题目解析:寻找规律
参考网址:【LeetCode】36. Valid Sudoku
根据上述网址中的代码,得到了以下几个思路。
- 首先,不考虑九宫格内是否有重复,需要考虑这个元素所在的行和列是否有重复的数字。这里需要遍历18个(当前位置看作两个数据)数据,所以可以用两个数组的位置来表示当前数字是否出现过。
- 其次,考虑怎么进行遍历呢?如果每次遍历一列或者一行,那么需要遍历9行和9列。有一个想法是将矩阵对角线上的数据作为对称中心,第i行j列的数据对角线的数据为第j行i列,具体的想法如图:
剩下的有关九宫格的参见上面的链接;
C++代码:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for (int i = 0; i < 9; i++)
{
bool column[9], row[9], grid[9];
memset(column,false,sizeof(column));
memset(row,false,sizeof(row));
memset(grid,false,sizeof(grid));
for (int j = 0; j < 9; j++)
{
if (board[i][j] != '.')
{
int temp = board[i][j] - '1';
if (row[temp])
return false;
row[temp] = true;
}
if (board[j][i] != '.')
{
int temp = board[j][i] - '1';
if (column[temp])
return false;
column[temp] = true;
}
if(board[i/3*3+j/3][i%3*3+j%3] != '.')
{
int temp = board[i/3*3+j/3][i%3*3+j%3] - '1';
if(grid[temp])
return false;
grid[temp] = true;
}
}
}
return true;
}
};
Python代码:
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for i in range(9):
column = [False] * 9
row = [False] * 9
grid = [False] * 9
for j in range(9):
if board[i][j] != '.':
temp = int (board[i][j]) - int ('1')
if row[temp]:
return False
row[temp] = True;
if board[j][i] != '.':
temp = int (board[j][i]) - int ('1')
if column[temp]:
return False
column[temp] = True
if board[int(i/3)*3+int (j/3)][i%3*3+j%3] != '.':
temp = int (board[int(i/3)*3+int(j/3)][i%3*3+j%3]) - int ('1')
if(grid[temp]):
return False;
grid[temp] = True;
return True