LeetCode36 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. (Easy)
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
分析:
就是把行、列和每个九宫格分别判定即可。思路很简单,就是代码需要简化,自己的版本写起来比较复杂,但是感觉好读一些。
代码1:
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char>>& board) { 4 int flag[10] = {0}; 5 for (int i = 0; i < 9; ++i) { 6 memset(flag,0,sizeof(flag)); 7 for (int j = 0; j < 9; ++j) { 8 if (board[i][j] != '.') { 9 if (flag[board[i][j] - '0'] == 1) { 10 return false; 11 } 12 else { 13 flag[board[i][j] - '0'] = 1; 14 } 15 } 16 } 17 } 18 for (int i = 0; i < 9; ++i) { 19 memset(flag,0,sizeof(flag)); 20 for (int j = 0; j < 9; ++j) { 21 if (board[j][i] != '.') { 22 if (flag[board[j][i] - '0'] == 1) { 23 return false; 24 } 25 else { 26 flag[board[j][i] - '0'] = 1; 27 } 28 } 29 } 30 } 31 for (int i = 0; i < 3; ++i) { 32 for (int j = 0; j < 3; ++j) { 33 memset(flag,0,sizeof(flag)); 34 for (int m = 3 * i; m < 3 * i + 3; ++m) { 35 for (int n = 3 * j; n < 3 * j + 3; ++n) { 36 if (board[m][n] != '.') { 37 if (flag[board[m][n] - '0'] == 1) { 38 return false; 39 } 40 else { 41 flag[board[m][n] - '0'] = 1; 42 } 43 } 44 } 45 } 46 } 47 } 48 return true; 49 } 50 };
代码2:
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char>>& board) { 4 for (int i = 0; i < 9; ++i) { 5 int flag1[10] = {0}; 6 int flag2[10] = {0}; 7 int flag3[10] = {0}; 8 int m = (i / 3) * 3 , n = (i % 3) * 3; 9 for (int j = 0; j < 9; ++j) { 10 if (board[i][j] != '.') { 11 if (flag1[board[i][j] - '0'] == 1) { 12 return false; 13 } 14 else { 15 flag1[board[i][j] - '0'] = 1; 16 } 17 } 18 if (board[j][i] != '.') { 19 if (flag2[board[j][i] - '0'] == 1) { 20 return false; 21 } 22 else { 23 flag2[board[j][i] - '0'] = 1; 24 } 25 } 26 int x = m + (j / 3); 27 int y = n + (j % 3); 28 if (board[x][y] != '.') { 29 if (flag3[board[x][y] - '0'] == 1) { 30 return false; 31 } 32 else { 33 flag3[board[x][y] - '0'] = 1; 34 } 35 } 36 } 37 } 38 return true; 39 } 40 };