LeetCode
程序员文章站
2022-04-27 11:48:58
...
20200330
题目 :有效的数独
判断一个9*9的数独是否有效。根据以下规则,验证已经填入的数字是否有效即可。
1. 数字1-9在每一行只能出现一次
2. 数字1-9在每一列只能出现一次
3. 数字1-9在每一个以粗实线分隔的3*3宫内只能出现一次
数独部分空格内已填入了数字,空白格用 '.'
表示。
示例:
输入:
[
["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
枚举子数独 :box_index = (row / 3)*3+columns / 3
;
code
class Solution{
public boolean isValidSudoku(char[][] board){
//记录
HashMap<Integer, Integer>[] rows = new HashMap[9];
HashMap<Integer,Integer>[] columns = new HashMap[9];
HashMap<Integer,Integer> [] boxes = new HashMap[9];
for(int i=0;i<9;i++){
rows[i] = new HashMap<Integer,Integer>();
columns[i] = new HashMap<Integer, Integer>();
boxes[i] = new HashMap<Integer,Integer>();
}
//一次迭代
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char num = board[i][j];
if(num != '.'){
int n = (int)num;
int box_index = (i / 3)*3 + j / 3;
//保存当前的单元值
rows[i].put(n,rows[i].getOrDefault(n,0)+1);
columns[j].put(n,columns[j].getOrDefault(n,0)+1);
boxes[box_index].put(n,boxes[box_index].getOrDefault(n,0)+1);
//判断当前值之前是否出现过
if(rows[i].get(n)>1 || columns[j].get(n) > 1 || boxes[box_index].get(n) > 1){
return false;
}
}
}
return true;
}
}
推荐阅读
-
【leetcode】127. Word Ladder
-
LeetCode Palindrome Partitioning
-
POJ3126 Prime Path(BFS) 类似于Leetcode 单词接龙
-
LeetCode#773滑动谜题
-
LeetCode 42: Trapping Rain Water题解(python)
-
leetcode:129. 求根到叶子节点数字之和(深搜)s
-
leetcode:417. 太平洋大西洋水流问题(深搜)
-
leetcode:547. 朋友圈(深搜)
-
leetcode:101. 对称二叉树(深搜)
-
Leetcode 1091. 二进制矩阵中的最短路径 八个方向寻路最短路径 (BFS)