leetcode之36有效的数独Golang
对于9*9的数独,我们按照行9个,列9个和3*3的子数独9个,因此一共有27个子数独,我们只需要判断这27个子数独中是否存在重复元素就解决了这一道题
行号0-8,列号0-8,我们按照从左到右从上到下,将3*3的子数独编号
| 0 | 1 | 2 |
|---|---|---|
| 3 | 4 | 5 |
| 6 | 7 | 8 |
那么我们按照行号和列号获取子数独编号的公式为:
(row/3)*3+column/3
其中/为整除
所以我们的目的就是当遍历到第i行,第j列的元素的时候,只要判断他在第i行和第j列以及(i/3)*3+j/3这三个子数独中是否出现过就OK了
算法
-
定义三个
map[byte]bool数组,每个数组中有9个map,分别是行、列和子数独的map -
遍历
9*9数独中的元素,行号为row,列号为column-
如果在行
row,列column,子数独(row/3)*3+column/3这三个数独中都是第一次出现,就将他们存入各自对应的map,就继续遍历下一个元素 -
如果在其中任何一个不是第一次出现,就返回
false
-
-
遍历完整个
9*9的数独以后就返回true
代码
func isValidSudoku(board [][]byte) bool {
rowMaps := make([]map[byte]bool, 9)
columnMaps := make([]map[byte]bool, 9)
subMaps := make([]map[byte]bool, 9)
for i := 0; i < 9; i++ {
rowMaps[i] = make(map[byte]bool)
columnMaps[i] = make(map[byte]bool)
subMaps[i] = make(map[byte]bool)
}
for row := 0; row < 9; row++ {
for column := 0; column < 9; column++ {
tmpChar := board[row][column]
if tmpChar == '.' {
continue
}
// 只有在行、列、子数独中都不满足才能进行下一步
if rowMaps[row][tmpChar] == true ||
columnMaps[column][tmpChar] == true ||
subMaps[(row/3)*3+column/3][tmpChar] == true {
return false
}
// 在行、列、子数独中都添加这个元素
rowMaps[row][tmpChar] = true
columnMaps[column][tmpChar] = true
subMaps[(row/3)*3+column/3][tmpChar] = true
}
}
return true
}
浙公网安备 33010602011771号