题目:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
分析:
每一行,每一列没有相同的数字,每一个3*3的小正方形中也没有相同的数字。可以使用数组,map,set等等来判断。
程序:
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { map<char,int> m; for (int i = 0; i < 9; i++){ for (int j = 0; j < 9; j++){ if (board[i][j] != '.'){ if (m[board[i][j]]) return false; m[board[i][j]]++; } } m.clear(); } for (int i = 0; i < 9; i++){ for (int j = 0; j < 9; j++){ if (board[j][i] != '.'){ if (m[board[j][i]]) return false; m[board[j][i]]++; } } m.clear(); } for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ for (int r = i*3; r < i*3+3; r++){ for (int l = j*3; l < j*3+3; l++){ if (board[r][l] != '.'){ if (m[board[r][l]]) return false; m[board[r][l]]++; } } } m.clear(); } } return true; } };