【算法】【线性表】【数组】有效的数独
1 题目
请你判断一个 9 x 9
的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。(请参考示例图)
注意:
- 一个有效的数独(部分已被填充)不一定是可解的。
- 只需要根据以上规则,验证已经填入的数字是否有效即可。
- 空白格用
'.'
表示。
示例 1: 输入:board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] 输出:true
示例 2: 输入:board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] 输出:false 解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
提示:
board.length == 9
board[i].length == 9
board[i][j]
是一位数字(1-9
)或者'.'
2 解答
记住,别憨憨的去解题,比如空白的应该是多少,别去解,因为题目中说不一定有解的,只需要遍历围绕它的三个特征去遍历判断即可:
class Solution { public boolean isValidSudoku(char[][] board) { // 存放行的计数 表示第几行 0-8 Map<Integer, Set<Integer>> rowMap = new HashMap(); // 存放列的计数 key 表示第几列 0-8 Map<Integer, Set<Integer>> columnMap = new HashMap(); // 存放3*3的计数 Map<String, Set<Integer>> tableMap = new HashMap(); for (int i=0; i<board.length; i++) { for (int j=0; j<board[i].length; j++) { char c = board[i][j]; // 如果当前坐标下,数字为空略过 if (c == '.') { continue; } // 巧妙得到字符对应的数字 int num = c - '0' + 1; // 放入列计数器 Set<Integer> columnSet = columnMap.computeIfAbsent(j, (val) -> new HashSet<Integer>()); // 当前列存在重复数字直接返回 false if (columnSet.contains(num)) { return false; } columnSet.add(num); // 放入行计数器 Set<Integer> rowSet = rowMap.computeIfAbsent(i, (val) -> new HashSet<Integer>()); // 当前列存在重复数字直接返回 false if (rowSet.contains(num)) { return false; } rowSet.add(num); // 放入九宫格计数器 int tableI = i / 3; int tableJ = j / 3; Set<Integer> tableSet = tableMap.computeIfAbsent(String.format("%s-%s", tableI, tableJ), (val) -> new HashSet<Integer>()); // 当前列存在重复数字直接返回 false if (tableSet.contains(num)) { return false; } tableSet.add(num); } } // 遍历完都符合,返回 true return true; } }
加油。