LeetCodeHot100_36——《有效的数独》
读题思路:
思路其实就是在分别建立行、列、小九宫格三类哈希结构,遍历的过程中判断里面出现的次数,如果有数字出现的次数大于1的话,那就返回false,否则就返回true;
具体代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool isValidSudoku(vector<vector<char>>& board) {
int rows[9][9]; //定义行,用来统计行中出现的数字的次数
int columns[9][9];//定义列,用来统计列中出现的数字的次数
int nineSquares[3][3][9];//定义九宫格,用来统计小九宫格中出现的数字的次数
memset(rows, 0, sizeof(rows));
memset(columns, 0, sizeof(columns));
memset(nineSquares, 0, sizeof(nineSquares));
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
char c = board[i][j];
if (c!='.') //如果遍历过程中出现了数字的话
{
int index = c - '0' - 1;
rows[i][index]++; //rows[i][index]表示的是第i行这个index这个数字出现的次数
columns[j][index]++;//columns[j][index]表示的是第i行这个index这个数字出现的次数
nineSquares[i / 3][j / 3][index]++; //小九宫格中index出现的次数
if (rows[i][index] > 1 || columns[j][index] > 1 || nineSquares[i / 3][j / 3][index] > 1) {
return false;
}
}
}
}
return true;
}
int main() {
vector<vector<char>> board = {
{'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'}};
cout << isValidSudoku(board);
return 0;
}