• 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);
        }
    
    }
  • 相关阅读:
    asp.net读取/导入project(mpp)文件
    hdu2103
    hdu2100(大数加)
    hdu1406
    hdu1249
    hdu1038
    hdu2565
    hdu1203
    zoj3501
    hdu2102
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11271454.html
Copyright © 2020-2023  润新知