前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >36. 有效的数独--题解

36. 有效的数独--题解

作者头像
付威
发布2021-04-25 10:10:51
3650
发布2021-04-25 10:10:51
举报
文章被收录于专栏:老付的网络博客
36. 有效的数独

难度中等506收藏分享切换为英文接收动态反馈

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

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

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

注意:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。

示例 1:

代码语言:javascript
复制
输入:board = 
[["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:

代码语言:javascript
复制
输入:board = 
[["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 存在, 因此这个数独是无效的。

提示:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] 是一位数字或者 '.'

题解

思路:

  1. 使用一个维度相同的二位数组,把当前数独中的值映射到新数组中
  2. 如果数组的值为 1 ,代表是重复,否则是个新值
  3. index_box 代表是同一个 3*3 的单元内都是一个索引
代码语言:javascript
复制

func isValidSudoku(board [][]byte) bool {
	var row,col,sbox [9][9]int
	for i := 0 ; i < 9; i++ {
		for j := 0 ; j < 9; j++ {
			if board[i][j] != '.' {
				//代表当前的索引
				num := board[i][j]-'1'
				index_box := (i/3)*3+j/3
				if row[i][num] == 1 {
					return false
				}else{
					row[i][num] = 1
				}
				if col[j][num] == 1 {
					return false
				}else{
					col[j][num] = 1
				}
				if sbox[index_box][num] == 1 {
					return false
				}else {
					sbox[index_box][num] = 1
				}
			}
		}
	}
	return true
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-04-242,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 36. 有效的数独
  • 题解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档