Leetcode36. 有效的数独
题目:
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 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
题解:
可以使用 box_index = (row / 3) * 3 + columns / 3,其中 / 是整数除法。
scala代码:
/**
*
* @param board
* @return
*/
def isValidSudoku(board: Array[Array[Char]]): Boolean = {
val row = new Array[mutable.HashMap[Int, Int]](9)
val col = new Array[mutable.HashMap[Int, Int]](9)
val box = new Array[mutable.HashMap[Int, Int]](9)
for(i<-0 until 9){
row(i)= new mutable.HashMap[Int,Int]()
col(i)= new mutable.HashMap[Int,Int]()
box(i)= new mutable.HashMap[Int,Int]()
}
var flag = true
for (i <- 0 until 9; if (flag)) {
for (j <- 0 until 9; if (flag)) {
val char = board(i)(j)
if (char != '.') {
val num: Int = char-'0'
val box_index = (i / 3) * 3 + (j / 3)
row(i).put(num, row(i).getOrElse(num, 0) + 1)
col(j).put(num, col(j).getOrElse(num, 0) + 1)
box(box_index).put(num, box(box_index).getOrElse(num, 0) + 1)
if (row(i).getOrElse(num, 0) > 1 || col(j).getOrElse(num, 0) > 1 || box(box_index).getOrElse(num, 0) > 1) {
flag = false
}
}
}
}
flag
}
来源:CSDN
作者:会流泪de鱼
链接:https://blog.csdn.net/sunhaiting666/article/details/104837000