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,其中 / 是整数除法。
java代码:
public static boolean isValidSudoku(char[][] board) {
int[][] row = new int[9][9];
int[][] col = new int[9][9];
int[][][] box = new int[3][3][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c != '.') {
int index = c - '0' - 1;
row[i][index]++;
col[j][index]++;
box[i / 3][j / 3][index]++;
if (row[i][index] > 1 || col[j][index] > 1 || box[i / 3][j / 3][index] > 1) {
return false;
}
}
}
}
return true;
}
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
}