-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.go
77 lines (67 loc) · 1.22 KB
/
solution.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
package lc2133
func checkValid(matrix [][]int) bool {
n := len(matrix)
if n == 0 {
return true
}
if n == 1 {
if matrix[0][0] == 1 {
return true
}
return false
}
set := newSetMatrix(n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
num := matrix[i][j]
set.addRow(i, num)
set.addCol(j, num)
}
}
return set.isEmpty()
}
type setMatrix struct {
rows [][]bool
cols [][]bool
count int
capacity int
}
func newSetMatrix(capacity int) *setMatrix {
return &setMatrix{
rows: make([][]bool, capacity, capacity),
cols: make([][]bool, capacity, capacity),
count: capacity * capacity * 2,
capacity: capacity,
}
}
func (s *setMatrix) addRow(row, num int) {
num -= 1
if num < 0 || num >= s.capacity {
return
}
if s.rows[row] == nil {
s.rows[row] = make([]bool, s.capacity, s.capacity)
}
if s.rows[row][num] {
return
}
s.rows[row][num] = true
s.count--
}
func (s *setMatrix) addCol(col, num int) {
num -= 1
if num < 0 || num >= s.capacity {
return
}
if s.cols[col] == nil {
s.cols[col] = make([]bool, s.capacity, s.capacity)
}
if s.cols[col][num] {
return
}
s.cols[col][num] = true
s.count--
}
func (s *setMatrix) isEmpty() bool {
return s.count == 0
}