36. 有效的数独 Valid Sudoku

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

方法:

遍历9*9的二维矩阵即可,将出现的数据放在map里

 

复制代码
public boolean isValidSudoku(char[][] board) {
        Map<Integer,Map<Character,Integer>> rows = new HashMap<>();
        Map<Integer,Map<Character,Integer>> cols = new HashMap<>();
        Map<Integer,Map<Character,Integer>> block = new HashMap<>();
        for (int i = 0; i < 9; i++){
            Map<Character,Integer> rowMap= new HashMap<>();
            rows.put(i,rowMap);
            Map<Character,Integer> colMap= new HashMap<>();
            cols.put(i,colMap);
            Map<Character,Integer> blockMap= new HashMap<>();
            block.put(i,blockMap);
        }
        for (int i =0 ;i < 9; i++){
            for(int j = 0; j < 9; j++){
                if (board[i][j] == '.') continue;
                if (rows.get(i).containsKey(board[i][j])) return false;
                else rows.get(i).put(board[i][j],1);
                if (cols.get(j).containsKey(board[i][j])) return false;
                else cols.get(j).put(board[i][j],1);
                if(block.get(i/3*3+j/3).containsKey(board[i][j])) return false;
                else block.get(i/3*3+j/3).put(board[i][j],1);
            }
        }

        return true;
    }
复制代码

 

参考链接:

https://leetcode.com/problems/valid-sudoku/

https://leetcode-cn.com/problems/valid-sudoku/

posted @   diameter  阅读(99)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示