leetcode-36-有效的数独

问题:

 

package com.example.demo;

import java.util.HashMap;
import java.util.Map;

public class Test36 {
    /**
     * 思路:
     * 构建多个map,二维数组中,每一行是一个map,每一行是一个map,在一个3*3的方格是一个map
     * 在遍历二维数组的时候,将当前索引代表的值放入到不同的map中,
     * 同时在每次添加进map后,判断当前map中是否已经有重复的字符了
     * Map<Integer,Integer>:key表示是哪个数,value代表出现过几次
     */
    public boolean isValidSudoku(char[][] board) {
        Map<Integer, Integer>[] row = new HashMap[9];
        Map<Integer, Integer>[] column = new HashMap[9];
        Map<Integer, Integer>[] box = new HashMap[9];

        // 初始化数组
        for (int i = 0; i < 9; i++) {
            row[i] = new HashMap<>();
            column[i] = new HashMap<>();
            box[i] = new HashMap<>();
        }

        // 遍历数组,将每一行中的字符代表的数字放入map中,并将出现的次数自增
        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;
                    // 行内,将当前字符(数字)作为key放入map中,如果原来有则加1,没有则当前置为1
                    row[i].put(n, row[i].getOrDefault(n, 0) + 1);
                    column[j].put(n, column[j].getOrDefault(n, 0) + 1);
                    // 当前i,j属于第几个3*3的方格
                    int boxIndex = (i / 3) * 3 + j / 3;
                    box[boxIndex].put(n, box[boxIndex].getOrDefault(n, 0) + 1);

                    //判断每个map中的value是否大于1,如果大于则代表出现过多次
                    if (row[i].get(n) > 1 || column[j].get(n) > 1 || box[boxIndex].get(n) > 1) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Test36 t = new Test36();
        char[][] arr = {
                {'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'}
        };
        boolean validSudoku = t.isValidSudoku(arr);
        System.out.println(validSudoku);
    }

}

 

转载于:https://www.cnblogs.com/nxzblogs/p/11271454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值