题目链接: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. iOS可视化动态绘制连通图

    上篇博客<iOS可视化动态绘制八种排序过程>可视化了一下一些排序的过程,本篇博客就来聊聊图的东西.在之前的博客中详细的讲过图的相关内容,比如<图的物理存储结构与深搜.广搜>.当 ...

  2. 前端开发中SEO的十二条总结

    一. 合理使用title, description, keywords二. 合理使用h1 - h6, h1标签的权重很高, 注意使用频率三. 列表代码使用ul, 重要文字使用strong标签四. 图片 ...

  3. 加深一下BlockingQueue的认识

    认识BlockingQueue BlockingQueue是一种可以阻塞线程的队列,java中对这种队列提供了方法抽象,BlockingQueue则是抽象的接口. add:添加元素到队列里,添加成功返 ...

  4. TODO:Laravel增加验证码

    TODO:Laravel增加验证码1. 先聊聊验证码是什么,有什么作用?验证码(CAPTCHA)是"Completely Automated Public Turing test to te ...

  5. Linux CentOS 配置Tomcat环境

    一.下载Tomcat 下载Tomcat方式也有两种,可以参考我的前一篇博文Linux CentOS配置JDK环境,这边就不再赘述. 二.在Linux处理Tomcat包 1.创建tomcat文件夹 mk ...

  6. myeclipse学习总结一(在MyEclipse中设置生成jsp页面时默认编码为utf-8编码)

    1.每次我们在MyEclispe中创建Jsp页面,生成的Jsp页面的默认编码是"ISO-8859-1".在这种情况下,当我们在页面中编写的内容存在中文的时候,就无法进行保存.如下图 ...

  7. 如何利用ETW(Event Tracing for Windows)记录日志

    ETW是Event Tracing for Windows的简称,它是Windows提供的原生的事件跟踪日志系统.由于采用内核(Kernel)层面的缓冲和日志记录机制,所以ETW提供了一种非常高效的事 ...

  8. 谈谈一些有趣的CSS题目(六)-- 全兼容的多列均匀布局问题

    开本系列,谈谈一些有趣的 CSS 题目,题目类型天马行空,想到什么说什么,不仅为了拓宽一下解决问题的思路,更涉及一些容易忽视的 CSS 细节. 解题不考虑兼容性,题目天马行空,想到什么说什么,如果解题 ...

  9. 在Linux系统下运行微信Web开发者工具

    微信Web开发者工具只有window版本和mac版本,如果想要在Linux系统下运行微信Web开发者工具,需要花费很大周折. 注:带 * 的步骤或文件为不确定是否管用的步骤或文件.本人系统为Linux ...

  10. 现代3D图形编程学习-基础简介(3)-什么是opengl (译)

    本书系列 现代3D图形编程学习 OpenGL是什么 在我们编写openGL程序之前,我们首先需要知道什么是OpenGL. 将OpenGL作为一个API OpenGL 通常被认为是应用程序接口(API) ...