题目要求:Valid Sudoku
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 '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
分析:
本题是让写数独的check函数(isValidSudoku)~基本有三个步骤:
① 每一行都合法;
② 每一列都合法;
③ 每一块都合法(3 * 3)。
代码如下:
class Solution { public: bool isValidSudoku(vector<vector<char> > &board) { // Start typing your C/C++ solution below // DO NOT write int main() function return isValidRow(board) && isValidColumn(board) && isValidBox(board); } private: bool isValidRow(vector<vector<char> > &board) { int count[9]; for (int i = 0; i < 9; i++) { memset(count, 0, sizeof(int) * 9); for (int j = 0; j < 9; j++) { if (!add(count, board[i][j])) { return false; } } } return true; } bool isValidColumn(vector<vector<char> > &board) { int count[9]; for (int i = 0; i < 9; i++) { memset(count, 0, sizeof(int) * 9); for (int j = 0; j < 9; j++) { if (!add(count, board[j][i])) { return false; } } } return true; } bool isValidBox(vector<vector<char> > &board) { int point[9][2] = { {1, 1}, {1, 4}, {1, 7}, {4, 1}, {4, 4}, {4, 7}, {7, 1}, {7, 4}, {7, 7} }; int dir[8][2] = { {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1} }; int count[10]; for (int i = 0, x, y; i < 9; i++) { memset(count, 0, sizeof(int) * 10); x = point[i][0]; y = point[i][1]; add(count, board[x][y]); for (int j = 0; j < 8; j++) { if (!add(count, board[dir[j][0] + x][dir[j][1] + y])) { return false; } } } return true; } bool add(int count[], char c) { if (c == '.') { return true; } //如果每个字符出现次数 <= 1,则正常+_+ return (++count[c - '1']) <= 1; } };
简化版本:
class Solution { public: bool isValidSudoku(vector<vector<char> > &board) { // Note: The Solution object is instantiated only once. vector<vector<bool>> rows(9, vector<bool>(9,false)); vector<vector<bool>> cols(9, vector<bool>(9,false)); vector<vector<bool>> blocks(9, vector<bool>(9,false)); for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++){ if(board[i][j] == '.')continue; //rows, cols, blocks分别是9个布尔值 //将每个点分别赋值为true //若未赋值的为true了,则有问题 int num = board[i][j] - '1'; if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num]) return false; rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true; } return true; } };