-
Notifications
You must be signed in to change notification settings - Fork 549
/
Copy pathvalid-sudoku.go
executable file
·86 lines (76 loc) · 1.46 KB
/
valid-sudoku.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package Problem0036
import "fmt"
func isValidSudoku(board [][]byte) bool {
for row := 0; row < 9; row++ {
if !isValidSudokuRow(board, row) {
return false
}
}
for col := 0; col < 9; col++ {
if !isValidSudokuCol(board, col) {
return false
}
}
for pod := 0; pod < 9; pod++ {
if !isValidSudokuPod(board, pod) {
return false
}
}
return true
}
func isValidSudokuRow(board [][]byte, row int) bool {
var nums [10]bool
for col := 0; col < 9; col++ {
n := convertToNumber(board[row][col])
if n < 0 {
continue
}
if nums[n] {
fmt.Println("Invalid row: ", row)
return false
}
nums[n] = true
}
return true
}
func isValidSudokuCol(board [][]byte, col int) bool {
var nums [10]bool
for row := 0; row < 9; row++ {
n := convertToNumber(board[row][col])
if n < 0 {
continue
}
if nums[n] {
fmt.Println("Invalid col: ", col)
return false
}
nums[n] = true
}
return true
}
func isValidSudokuPod(board [][]byte, pod int) bool {
var nums [10]bool
row := (pod / 3) * 3
col := (pod % 3) * 3
for drow := 0; drow < 3; drow++ {
for dcol := 0; dcol < 3; dcol++ {
n := convertToNumber(board[row+drow][col+dcol])
if n < 0 {
continue
}
if nums[n] {
fmt.Println("Invalid pod:", pod)
fmt.Printf("Found duplicate number %d on row %d, col %d", n, row+drow, col+dcol)
return false
}
nums[n] = true
}
}
return true
}
func convertToNumber(b byte) int {
if b == '.' {
return -1
}
return int(b - '0')
}