我用三个9*9的矩阵存储9行,9列,9个box里,1~9出现过的情况,值得注意的是,board[i][j]是char各式,想要其作为下标索引,需要做这步处理
row[i][board[i][j]-'0'-1] ++;
完整代码如下
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][9] = { 0 };
int column[9][9] = { 0 };
int box[9][9] = { 0 };
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {//单引号为字符,双引号为字符串
row[i][board[i][j]-'0'-1] ++;
column[j][board[i][j]-'0'-1] ++;
box[(i / 3) * 3 + (j / 3)][board[i][j]-'0'-1] ++;
if (row[i][board[i][j]-'0'-1] == 2 || column[j][board[i][j]-'0'-1] == 2 || box[(i / 3) * 3 + (j / 3)][board[i][j]-'0'-1] == 2) {
return false;
}
}
}
}
return true;
}
};
int main() {
Solution test;
vector<vector<char>>board =
{ {'5','9','.','.','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'} };
cout << test.isValidSudoku(board);
}