Leetcode刷题100天—36. 有效的数独(数组+哈希)—day26
Posted 神的孩子都在歌唱
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题100天—36. 有效的数独(数组+哈希)—day26相关的知识,希望对你有一定的参考价值。
前言:
作者:神的孩子在歌唱
大家好,我叫运智
36. 有效的数独
难度中等575
请你判断一个 9x9
的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字
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]
是一位数字或者'.'
package 数组;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.omg.CORBA.PUBLIC_MEMBER;
public class _36_有效的数独 {
//通过哈希表判断是否有重复的数字,在通过for循环一个个遍历
public boolean isValidSudoku(char[][] board) {
// 通过哈希映射,如果有数大于2的就返回false
// 我们这里设置存储列的哈希,行的哈希和子独数的哈希
HashMap<Integer, Integer>[] rows=new HashMap[9];//行
HashMap<Integer, Integer>[] colums=new HashMap[9];//列
HashMap<Integer, Integer>[] boxes=new HashMap[9];//子独数
// 由于这里是九行九列,所以我们要遍历一下给每个都设置一个哈希空间
for(int i=0;i<9;i++) {
rows[i]=new HashMap<>();
colums[i]=new HashMap<>();
boxes[i]= new HashMap<>();
}
// 先遍历每一行,在遍历每一列
for(int row=0;row<9;row++){
// 遍历每行每一列
for(int colum=0;colum<9;colum++) {
// 或去row行colum列的值
char num=board[row][colum];
// 如果不是.号就转化为数字存入哈希中
if (num!='.') {
int n=(int)num;
// 存入每一行
rows[row].put(n, rows[row].getOrDefault(n, 0)+1);
// 存入每一列
colums[colum].put(n, colums[colum].getOrDefault(n, 0)+1);
// 设定每一个小独数,跟人工智能的
int box_index=(row/3)*3+(colum/3);
// 存入每一个小独数的元素
boxes[box_index].put(n, boxes[box_index].getOrDefault(n, 0)+1);
// 在判断一下这三个哈希表的值是否存在大于1的,因为大于一就说明有重复的值
if (rows[row].get(n)>1||colums[colum].get(n)>1||boxes[box_index].get(n)>1) {
return false;
}
}
}
}
return true;
}
}
本人csdn博客:https://blog.csdn.net/weixin_46654114
转载说明:跟我说明,务必注明来源,附带本人博客连接。
以上是关于Leetcode刷题100天—36. 有效的数独(数组+哈希)—day26的主要内容,如果未能解决你的问题,请参考以下文章