【LeetCode36. 有效的数独】

  1. 有效的数独
    请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

在这里插入图片描述
方案一:

 private static boolean isValidSudoku(char[][] board) {
        Map<Integer, Set<Integer>> row = new HashMap<>();
        Map<Integer, Set<Integer>> col = new HashMap<>();
        Map<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++) {
                if (board[i][j] == '.') {
                    continue;
                }
                int temp = board[i][j] - '0';
                //计算area区域
                int index = i / 3 * 3 + j / 3;
                if (row.get(i).contains(temp) || col.get(j).contains(temp) ||
                        area.get(index).contains(temp)) {
                    return false;
                }
                row.get(i).add(temp);
                col.get(j).add(temp);
                area.get(index).add(temp);

            }
        }
        return true;
    }

方案二:
private static boolean isValidSudoku2(char[][] board) {
//用数组来进行优化 ->只需要判断每一位存在是符合条件
boolean[][] row = new boolean[10][10],col = new boolean[10][10],area = new boolean[10][10];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == ‘.’) {
continue;
}
int temp = board[i][j] - ‘0’;
int index = i / 3 * 3 + j / 3;
if (row[i][temp] || col[j][temp] || area[index][temp]) {
return false;
}
row[i][temp]= col[j][temp]=area[index][temp] = false;
}
}
return true;
}

特此:感谢【宫水三叶】
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值