根据数独的规则Sudoku Puzzles - The Rules.判断给出的局面是不是一个符合规则的数独局面
数独盘面可以被部分填写,空的位置用字符'.'.表示
这是一个部分填写的符合规则的数独局面
class Solution { public boolean isValidSudoku(char[][] board) { boolean[][] rowVisited = new boolean[9][9]; boolean[][] colVisited = new boolean[9][9]; boolean[][] blockVisited = new boolean[9][9]; for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ char c = board[i][j]; if(c == '.'){ continue; } int num = c - '0' - 1; if(rowVisited[i][num] || colVisited[j][num] || blockVisited[i / 3 * 3 + j / 3][num]){ return false; } rowVisited[i][num] = true; colVisited[j][num] = true; blockVisited[i / 3 * 3 + j / 3][num] = true; } } return true; } }
*用空间换时间 *大部分答案都是建立3个set,遍历3次 *这里建立27个set,只需遍历一次 * 不清楚这样做好不好,求指点 public boolean isValidSudoku(char[][] board) { Set[] row = new HashSet[9]; Set[] col = new HashSet[9]; Set[] cube = new HashSet[9]; for (int i = 0; i < 9; i++) { row[i] = new HashSet(); col[i] = new HashSet(); cube[i] = new HashSet(); } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if(board[i][j] != '.' && !( row[i].add(board[i][j]) && col[j].add(board[i][j]) && cube[3*(i/3)+j/3].add(board[i][j]) )){ return false; } } return true; }
public boolean isValidSudoku(char[][] board) { for(int i = 0; i<9; i++){ HashSet<Character> rows = new HashSet<Character>(); HashSet<Character> columns = new HashSet<Character>(); HashSet<Character> cube = new HashSet<Character>(); for (int j = 0; j < 9;j++){ if(board[i][j]!='.' && !rows.add(board[i][j])) return false; if(board[j][i]!='.' && !columns.add(board[j][i])) return false; int RowIndex = 3*(i/3); int ColIndex = 3*(i%3); if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) return false; } } return true; }