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.
题目中说的,只要当前已经填充的数字是合法的就可以,不一定要这个数独是有解.(下面说的九宫格都是指3*3的网格)
因此只需要判断9*9网格的每一行、每一列、9个小九宫格是否合法。即如果在每一行、每一列、每个9个小九宫格内,某个数字重复出现了,当前数独就是不合法的。
bool isValidSudoku(vector<vector<char> > &board) { // Note: The Solution object is instantiated only once. int row[9],col[9]; for(int i = 0; i < 9; i++) { memset(row,0,sizeof(int)*9); memset(col,0,sizeof(int)*9); for(int j = 0; j < 9; j++) { if(board[i][j] != '.') { if(row[board[i][j]-'1'] > 0)return false; else row[board[i][j]-'1']++; } if(board[j][i] != '.') { if(col[board[j][i]-'1'] > 0)return false; else col[board[j][i]-'1']++; } } } for(int i = 0; i < 9; i+=3) for(int j = 0; j < 9; j+=3) { memset(row,0,sizeof(int)*9); for(int a = 0; a < 3; a++) for(int b= 0; b < 3; b++) if(board[i+a][j+b] != '.') { if(row[board[i+a][j+b]-'1']>0)return false; else row[board[i+a][j+b]-'1']++; } } return true; }
public boolean isValidSudoku(char[][] board) { boolean[] visited = new boolean[10]; //row for(int i=0; i<9; i++) { Arrays.fill(visited, false); for(int j=0; j<9; j++) { if( !check(visited, board[i][j]) ) { return false; } } } //col for(int i=0; i<9; i++) { Arrays.fill(visited, false); for(int j=0; j<9; j++) { if( !check(visited, board[j][i]) ) { return false; } } } //sub matrix for(int i=0; i<9; i+=3) { for(int j=0; j<9; j+=3) { Arrays.fill(visited, false); for(int k=0; k<9; k++) { if( !check(visited, board[i+k/3][j+k%3]) ) { return false; } } } } return true; } private boolean check(boolean[] visited, char c) { if(c == '.') { return true; } int num = c - '0'; if(num<1 || num>9 ||visited[num]) { return false; } else { visited[num] = true; } return true; }