题目链接: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. ASP.NET Aries 入门开发教程6:列表数据表格的格式化处理及行内编辑

    前言: 为了赶进度,周末也写文了! 前几篇讲完查询框和工具栏,这节讲表格数据相关的操作. 先看一下列表: 接下来我们有很多事情可以做. 1:格式化 - 键值的翻译 对于“启用”列,已经配置了格式化 # ...

  2. 移动先行之谁主沉浮? 带着你的Net飞奔吧!

    移动系源码:https://github.com/dunitian/Windows10 移动系文档:https://github.com/dunitian/LoTDotNet/tree/master/ ...

  3. 前端学HTTP之内容协商

    前面的话 一个URL常常需要代表若干不同的资源.例如那种需要以多种语言提供其内容的网站站点.如果某个站点有说法语的和说英语的两种用户,它可能想用这两种语言提供网站站点信息.理想情况下,服务器应当向英语 ...

  4. C#创建dll类库

    类库让我们的代码可复用,我们只需要在类库中声明变量一次,就能在接下来的过程中无数次地使用,而无需在每次使用前都要声明它.这样一来,就节省了我们的内存空间.而想要在类库添加什么类,还需取决于类库要实现哪 ...

  5. C#日志

    参考页面: http://www.yuanjiaocheng.net/Entity/first.html http://www.yuanjiaocheng.net/Entity/jieshao.htm ...

  6. javascript高性能编程-算法和流程控制

          代码整体结构是执行速度的决定因素之一. 代码量少不一定运行速度快, 代码量多也不一定运行速度慢. 性能损失与代码组织方式和具体问题解决办法直接相关.       倒序循环可以提高性能,如: ...

  7. 服务治理要先于SOA

      讲在前面的话: 若企业缺乏对服务变更的控制和规则,那么一个服务在经过几个项目之后,就很有可能被随意更改成多个版本,将来变成什么样更是无法预测.久而久之,降低了服务重用的可能性,提高了服务利用的成本 ...

  8. 如何使用SHOW WARNINGS?

    1.show warnings:显示上一个语句的错误.警告以及注意.如图:

  9. SQL Server事务、视图和索引

    废话不多说,直接上干货 14:13:23 事务 概括:事务是一种机制,一个操作序列,包含一组数据库操作命令,并且把所有的命令作为一个整体一起 向系统提交或撤销操作 请求. 事务的特性:   1.原子性 ...

  10. join Linq

    List<Publisher> Publishers = new List<Publisher>(); Publisher publish1 = new Publisher() ...