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.
//方法:时间复杂度O(n^2),空间复杂度O(1) class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { bool used[9]; for(int i = 0; i < 9; i++) //分别表示从1~9行,和1~9列 { fill(used, used+9, false); //检查行 for(int j = 0; j < 9; j++) { if(!check(board[i][j], used)) return false; } fill(used, used+9, false); //检查列 for(int j = 0; j < 9; j++) { if(!check(board[j][i], used)) return false; } } for(int i = 0; i < 9; i += 3) //检查九3*3的正方形 for(int j = 0; j < 9; j += 3) { fill(used, used+9, false); for(int k = 0; k < 3; k++) for(int l = 0; l < 3; l++) { if(!check(board[i+k][j+l], used)) return false; } } return true; } bool check(char ch, bool used[9]) { if(ch == '.') return true; else if(used[ch - '1'] == false) { used[ch - '1'] = true; return true; } else if(used[ch - '1'] == true) return false; } };
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46591615