题目链接: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. 探究javascript对象和数组的异同,及函数变量缓存技巧

    javascript中最经典也最受非议的一句话就是:javascript中一切皆是对象.这篇重点要提到的,就是任何jser都不陌生的Object和Array. 有段时间曾经很诧异,到底两种数据类型用来 ...

  2. Database Replay和Consolidated Database replay

    简介 在数据库的迁移和升级场景中,我们经常会遇到一个问题:在做压力测试时,如何模拟真实的业务压力,解决这个问题的方法有很多,比如:应用方开发模拟程序或者使用压力测试工具模拟,如load runner, ...

  3. 简谈百度坐标反转至WGS84的三种思路

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 基于百度地图进行数据展示是目前项目中常见场景,但是因为百度地图 ...

  4. Socket聊天程序——客户端

    写在前面: 上周末抽点时间把自己写的一个简单Socket聊天程序的初始设计和服务端细化设计记录了一下,周二终于等来毕业前考的软考证书,然后接下来就是在加班的日子度过了,今天正好周五,打算把客户端的详细 ...

  5. load和initialize方法

      一.load 方法什么时候调用: 在main方法还没执行的时候 就会 加载所有类,调用所有类的load方法. load方法是线程安全的,它使用了锁,我们应该避免线程阻塞在load方法. 在项目中使 ...

  6. ASP.NET Core的路由[4]:来认识一下实现路由的RouterMiddleware中间件

    虽然ASP.NET Core应用的路由是通过RouterMiddleware这个中间件来完成的,但是具体的路由解析功能都落在指定的Router对象上,不过我们依然有必要以代码实现的角度来介绍一下这个中 ...

  7. [原] KVM 虚拟化原理探究 —— 目录

    KVM 虚拟化原理探究 -- 目录 标签(空格分隔): KVM KVM 虚拟化原理探究(1)- overview KVM 虚拟化原理探究(2)- QEMU启动过程 KVM 虚拟化原理探究(3)- CP ...

  8. spring的BeanFactory加载过程

    ApplicationContext spring = new ClassPathXmlApplicationContext("classpath*:spring/applicationCo ...

  9. 浅析SQL查询语句未显式指定排序方式,无法保证同样的查询每次排序结果都一致的原因

    本文出处:http://www.cnblogs.com/wy123/p/6189100.html 标题有点拗口,来源于一个开发人员遇到的实际问题 先抛出问题:一个查询没有明确指定排序方式,那么,第二次 ...

  10. [DJANGO] excel十几万行数据快速导入数据库研究

    先贴原来的导入数据代码: 8 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www.setting ...