博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:36. 有效的数独
阅读量:4959 次
发布时间:2019-06-12

本文共 2062 字,大约阅读时间需要 6 分钟。

1、题目描述

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

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

上图是一个部分填充的有效的数独。

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 1:

输入:[  ["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:

输入:[  ["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 存在, 因此这个数独是无效的。

说明:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 给定数独序列只包含数字 1-9 和字符 '.' 。
  • 给定数独永远是 9x9 形式的。

2、题解

2.1、解法一

class Solution:    def is_valid(self, new_list):        new_list = [i for i in new_list if i != "."]        return len(new_list) == len(set(new_list))    def isValidRow(self,board):        for i in board:            if not self.is_valid(i):                return False        return True    def isValidColumn(self,board):        for i in zip(*board):            if not self.is_valid(i):                return False        return True    def isValidSq(self,board):        for i in (0,3,6):            for z in (0,3,6):                tmp = [n  for j in  board[i:i+3] for n in j[z:z+3]]                if not self.is_valid(tmp):                    return False        return True    def isValidSudoku(self, board):        """        :type board: List[List[str]]        :rtype: bool        """        return self.isValidRow(board) and self.isValidColumn(board) and self.isValidSq(board)

  

转载于:https://www.cnblogs.com/bad-robot/p/10065217.html

你可能感兴趣的文章
混沌分形之迭代函数系统(IFS)
查看>>
边框圆角Css
查看>>
使用Busybox制作根文件系统
查看>>
jpg图片在IE6、IE7和IE8下不显示解决办法
查看>>
delphi之模糊找图
查看>>
Javascript模块化编程的写法
查看>>
大华门禁SDK二次开发(二)-SignalR应用
查看>>
oracle 使用job定时自动重置sequence
查看>>
集成百度推送
查看>>
在项目中加入其他样式
查看>>
在使用Kettle的集群排序中 Carte的设定——(基于Windows)
查看>>
【原】iOS中KVC和KVO的区别
查看>>
OMAPL138学习----DSPLINK DEMO解析之SCALE
查看>>
IoC的基本概念
查看>>
restframework CBV试图的4种方式
查看>>
大图居中,以1920px为例
查看>>
Python3 图片转字符画
查看>>
[C陷阱和缺陷] 第7章 可移植性缺陷
查看>>
人需要治愈
查看>>
linux中configure文件默认执行结果所在位置
查看>>