题目描述:
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
分析:
题意:给出一个数独游戏当前局面,判断此时填入的数字是否合法('.'表示空格,未填写)。
思路:数独游戏在一个9 * 9的界面上进行,判定规则:每一行、每一列、每一个3 * 3小矩阵内(共(9 * 9) / (3 * 3) = 9个小矩阵)的9个数字不重复,即为合法的。我们只需要对三条规则进行验证即可。采用set,判断是否存在重复数字('.'跳过),若存在,则非法;验证完成,不存在重复数字,则合法。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
// rows
for(int i = 0; i <= 8; i++){
set<char> s;
for(int j = 0; j <= 8; j++){
if(board[i][j] == '.'){
continue;
}
if(s.count(board[i][j])){
return false;
}
else{
s.insert(board[i][j]);
}
}
}
// columns
for(int i = 0; i <= 8; i++){
set<char> s;
for(int j = 0; j <= 8; j++){
if(board[j][i] == '.'){
continue;
}
if(s.count(board[j][i])){
return false;
}
else{
s.insert(board[j][i]);
}
}
}
// cubes
for(int i = 0; i <= 6; i += 3){
for(int j = 0; j <= 6; j += 3){
set<char> s;
for(int k = 0; k <= 2; k++){
for(int l = 0; l <= 2; l++){
if(board[i + k][j + l] == '.'){
continue;
}
if(s.count(board[i + k][j + l])){
return false;
}
else{
s.insert(board[i + k][j + l]);
}
}
}
}
}
return true;
}
};