leetcode题目例题解析(六)
Valid Sudoku
题目描述:
Determine if a Sudoku is valid
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
题意解析:
这道题就是判断一个给定的数独是否是合理的,这个数独可能是没有完成的,没有填的位置用‘.’来表示。
解题思路:
数独的规则有三个:
1.每一行的数不能有重复
2.每一列的数不能有重复
3.给定的九个方形的位置不能有重复
根据这三个规则分别判断就可以了,思路是给定的
代码:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//用一个数组表示一次判断过程中的数是否重复出现,每次使用前要先初始化
int appeared[10];
//判断行
for (int i = 0; i < 9; i++) {
for(int i = 0; i < 10; i++)
appeared[i] = 0;
for(int j = 0; j < 9; j++) {
if (board[i][j] != '.'){
if (appeared[board[i][j] - '0'] == 1)
return false;
else
appeared[board[i][j] - '0'] = 1;
}
}
}
//判断列
for (int i = 0; i < 9; i++) {
for(int k = 0; k < 10; k++)
appeared[k] = 0;
for(int j = 0; j < 9; j++) {
if (board[j][i] != '.'){
if (appeared[board[j][i] - '0'] == 1)
return false;
else
appeared[board[j][i] - '0'] = 1;
}
}
}
//判断方格
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for(int k = 0; k < 10; k++)
appeared[k] = 0;
for (int m = i*3; m < i*3 + 3; m++) {
for (int n = j*3; n < j*3+3; n++) {
if (board[m][n] != '.'){
if (appeared[board[m][n] - '0'] == 1)
return false;
else
appeared[board[m][n] - '0'] = 1;
}
}
}
}
}
return true;
}
};
原题目链接:
https://leetcode.com/problems/valid-sudoku/description/