题目链接:Valid Sudoku | LeetCode OJ

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Tags: Hash Table

分析

对于数独是否是合法的,依靠以下三个判断条件,注意数独是否合法与是否可解无关

  • 横行的数字均含1-9,不重复
  • 纵列的数字均含1-9,不重复
  • 每个粗线宫内的数字均含1-9,不重复
  • 除1-9外可以存在空格子,空格子用 “.” 表示

最简单直接的解法一般是遍历整张数独表格,遇到的每个元素,以此遍历所属行、所属列、所属粗线宫是否有与之重复的数字。

但是这种算法中,每遍历到一个元素,都要进行额外的最多3*9个格子的遍历。

这里可以采用空间换时间的做法,定义3个9*9布尔值哈希表如下:

  • rowMatrix[N][1~9]: 表示第N行中,1-9是否分别出现过
  • columnMatrix[N][1~9]: 表示第N列中,1-9是否分别出现过
  • groupMatrix[N][1~9]: 表示第N个粗线宫中,1-9是否分别出现过,N为从左向右、从上向下计数的粗线宫

这样遍历整张数独表格时,先检查在3个矩阵中该格子内的数字在对应哈希表中是否出现过,如果出现过,则数独不合法。遍历过的数字在对应矩阵中标为True

示例

# 数独表格宽度
width = 9 class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
rowMatrix = self.getValidMatrix()
columnMatrix = self.getValidMatrix()
groupMatrix = self.getValidMatrix() if len(board) != width:
return False for i in range(width):
if len(board[i]) != width:
return False for j in range(width):
if board[i][j] == '.':
continue cell = int(board[i][j]) - 1
# 检验行有效性
if rowMatrix[i][cell]:
return False
# 检验列有效性
if columnMatrix[j][cell]:
return False
# 检验粗线宫有效性
if groupMatrix[(i // 3) * 3 + j //3][cell]:
return False rowMatrix[i][cell] = True
columnMatrix[j][cell] = True
groupMatrix[(i // 3) * 3 + j //3][cell] = True return True def getValidMatrix(self):
result = []
for i in range(width):
result.append([])
for j in range(width):
result[i].append(False)
return result

Leetcode 笔记系列的Python代码共享在https://github.com/wizcabbit/leetcode.solution

常见问题

  • 空格子使用 “.” 表示,因此题目的输入项和处理格子时,均为字符串,这是在对格子的值进行处理时,如果不进行类型转换会出现低级错误,如:cell = int(board[i][j]) - 1
  • 在遍历每个格子时,对应的粗线宫索引为:groupMatrix[(i // 3) * 3 + j //3][cell]

相关题目

Sudoku Solver

Leetcode 笔记 35 - Valid Soduko的更多相关文章

  1. leetcode笔记——35.搜索插入位置 - CrowFea

    0.问题描述 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会被按顺序插入的位置. 你可以假设数组中无重复元素. 示例 1: 12 输入: [1,3 ...

  2. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  3. Leetcode 笔记 36 - Sudoku Solver

    题目链接:Sudoku Solver | LeetCode OJ Write a program to solve a Sudoku puzzle by filling the empty cells ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

随机推荐

  1. 前端CSS预处理器Sass

    前面的话   "CSS预处理器"(css preprocessor)的基本思想是,用一种专门的编程语言,进行网页样式设计,然后再编译成正常的CSS文件.SASS是一种CSS的开发工 ...

  2. 2D、3D形变

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 17.0px Monaco; color: #a5b2b9 } span.Apple-tab-span { ...

  3. 【翻译】MongoDB指南/CRUD操作(二)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...

  4. 步入angularjs directive(指令)--准备工作熟悉hasOwnProperty

    在讲解directive之前,先做一下准备工作,为何要这样呢? 因为我们不是简单的说说directive怎么用,还要知道为什么这么用!(今天我们先磨磨刀!). 首先我们讲讲js 基础的知识--hasO ...

  5. 深入理解 JavaScript,以及 Linux 下的开发调试工具

    前言 JavaScript 是我接触到的第二门编程语言,第一门是 C 语言.然后才是 C++.Java 还有其它一些什么.所以我对 JavaScript 是非常有感情的,毕竟使用它有十多年了.早就想写 ...

  6. 满堂红CIO邓劲翔:房屋中介突围

    人脸识别.客户关系管理进度监控.业务流程实时监控.网站访问人数及流量实时监控等实际企业应用场景淋漓尽致.羽羽如生的以大屏幕上图表形式展现在人们面前,如果你不去继续询问,你不会知道这是一家才刚刚在房地产 ...

  7. Kotlin中变量不同于Java: var 对val(KAD 02)

    原文标题:Variables in Kotlin, differences with Java. var vs val (KAD 02) 作者:Antonio Leiva 时间:Nov 28, 201 ...

  8. 海鑫智圣:物联网漫谈之MQTT协议

    什么是MQTT协议 MQTT(消息队列遥测传输协议)是IBM在1999年专门针对物联网等应用场景来制订的轻量级双向消息传输协议,它主要是为了解决物联网上使用到的设备的互相通信的问题,以及这些设备与后端 ...

  9. Oracle常用SQL函数整理

    --返回ASCII码select  ASCII('A') "A的ASCII码" ,ASCII('a') "a的ASSCII码" from dual ; --反向 ...

  10. linux下安装Redis以及phpredis模块

    一:redis的安装 1. 首先上官网下载Redis 压缩包,地址:http://redis.io/download 下载 2. 通过远程管理工具,将压缩包拷贝到Linux服务器中,执行解压操作 3. ...