1. 有效的数独(36)
请你判断一个 9 x 9
的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。(请参考示例图)
class Solution { public boolean isValidSudoku(char[][] board) { HashMap<Integer, Set<Integer>> row = new HashMap<>(); HashMap<Integer, Set<Integer>> col = new HashMap<>(); HashMap<Integer, Set<Integer>> area = new HashMap<>(); for (int i = 0; i < 9; i++) { row.put(i,new HashSet<>()); col.put(i,new HashSet<>()); area.put(i,new HashSet<>()); } for (int i = 0; i < 9; i++) { for (int j = 0; j <9 ; j++) { char c = board[i][j]; if(c=='.') continue; int u = c-'0'; int idx = i/3*3+j/3; if(row.get(i).contains(u)||col.get(j).contains(u)||area.get(idx).contains(u)) return false; row.get(i).add(u); col.get(j).add(u); area.get(idx).add(u); } } return true; } }
2.解数独
编写一个程序,通过填充空格来解决数独问题
class Solution { private boolean[][] line = new boolean[9][9]; private boolean[][] column = new boolean[9][9]; private boolean[][][] block = new boolean[3][3][9]; private boolean valid = false; private List<int[]> spaces = new ArrayList<int[]>(); public void solveSudoku(char[][] board) { for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (board[i][j] == '.') { spaces.add(new int[]{i, j}); } else { int digit = board[i][j] - '0' - 1; line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true; } } } recusiveSolveSudoku(board, 0); } public void recusiveSolveSudoku(char[][] board, int pos) { if (pos == spaces.size()) { valid = true; return; } int[] space = spaces.get(pos); int i = space[0], j = space[1]; for (int digit = 0; digit < 9 && !valid; ++digit) { if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) { line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true; board[i][j] = (char) (digit + '0' + 1); recusiveSolveSudoku(board, pos + 1); line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false; } } } }
标签:digit,HashMap,int,11.1,boolean,board,new,打卡 From: https://www.cnblogs.com/forever-fate/p/17804162.html