36. Valid Sudoku
LeetCode 36. Valid Sudoku
Description

Tags
Solution

Complexity
Code
Reference
Last updated


Last updated
Input: 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"]]
Output: trueInput: 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"]]
Output: false
Explanation: Same as Example 1,
except with the 5 in the top left corner being modified to 8.
Since there are two 8's in the top left 3x3 sub-box, it is invalid.func isValidSudoku(board [][]byte) bool {
rows, cols, boxes := [9][9]int{}, [9][9]int{}, [9][9]int{}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
if board[i][j] == '.' {
continue
}
boxIdx, v := i/3*3+j/3, board[i][j]-'1'
rows[i][v]++
cols[j][v]++
boxes[boxIdx][v]++
if rows[i][v] > 1 || cols[j][v] > 1 || boxes[boxIdx][v] > 1 {
return false
}
}
}
return true
}