当前位置: 首页 > article >正文

[LeetCode] 36. 有效的数独

题目描述:

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

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 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] 是一位数字(1-9)或者 '.'

题目链接:

. - 力扣(LeetCode)

解题主要思路:

其实这题跟 "N皇后" 那道题差不多,甚至可以说 "N皇后" 是这道题的升级版。我们只需要借助三个bool数组变量即可:

    bool row[9][10];  // 判断行
    bool col[9][10];  // 判断列
    bool grid[3][3][10];  // 判断3x3网格

之后遍历9x9网格,如果遇到数字,则判断它所在的行和列以及所在的3x3网格中是否是唯一存在即可。

解题代码:

class Solution {
public:
    bool row[9][10];  // 判断行
    bool col[9][10];  // 判断列
    bool grid[3][3][10];  // 判断3x3网格
    bool isValidSudoku(vector<vector<char>>& board) {
        // 遍历
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[0].size(); ++j) {
                if (board[i][j] != '.') {
                    int num = board[i][j] - '0';
                    if (row[i][num] || col[j][num] || grid[i/3][j/3][num]) return false;
                    else row[i][num] = col[j][num] = grid[i/3][j/3][num] = true;
                }
            }
        }
        return true;
    }
};


http://www.kler.cn/a/373745.html

相关文章:

  • 【jvm】堆的默认最大值和默认最小值的计算
  • C++笔记---可变参数模板
  • 链接动态库
  • 华为配置 之 STP
  • SQL语言基础
  • DGUS屏使用方法
  • JAVA的动态代理
  • 创新实践:基于边缘智能+扣子的智能取物机器人解决方案
  • DDRPHY数字IC后端设计实现系列专题之后端设计导入,IO Ring设计
  • Java中String的length与Oracle数据库中VARCHAR2实际存储长度不一致的问题
  • 【优选算法篇】前缀之美,后缀之韵:于数列深处追寻算法的动与静
  • 面试题:JVM(一)
  • 类和对象(中)—— 类的六个默认成员函数
  • 【面试题】Node.JS篇
  • 「MinIO快速入门」
  • nginx------正向代理,反向代理生产,以及能否不使用代理详解
  • SpringBoot + Shiro权限管理
  • Linux下EDAC功能介绍
  • Linux第二讲:Linux权限理解
  • 若依框架部署到服务器后头像资源访问404
  • 图片懒加载(自定义指令)
  • 共享内存相关知识点
  • 架构师备考-数据库基础
  • 安科瑞AM5SE-IS 防逆流保护装置 功能全面 逆功率保护
  • Linux安装部署数据库:MongoDB
  • Redis高级篇之bigKey理论介绍以及优化