-
Notifications
You must be signed in to change notification settings - Fork 17
/
possible-bipartition.go
67 lines (53 loc) · 1.2 KB
/
possible-bipartition.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
package main
func color(node int, adjList [][]int, colors []int, visited []bool) bool {
visited[node] = true
for _, adjNode := range adjList[node] {
if colors[node] == 0 && colors[adjNode] == 0 {
colors[node] = 1
colors[adjNode] = 2
}
if colors[node] == 1 {
if colors[adjNode] == 2 || colors[adjNode] == 0 {
colors[adjNode] = 2
if visited[adjNode] {
continue
}
if !color(adjNode, adjList, colors, visited) {
return false
}
} else {
return false
}
}
if colors[node] == 2 {
if colors[adjNode] == 1 || colors[adjNode] == 0 {
colors[adjNode] = 1
if visited[adjNode] {
continue
}
if !color(adjNode, adjList, colors, visited) {
return false
}
} else {
return false
}
}
}
return true
}
func possibleBipartition(n int, dislikes [][]int) bool {
colors := make([]int, n)
visited := make([]bool, n)
adjList := make([][]int, n)
for _, dislike := range dislikes {
src, dst := dislike[0]-1, dislike[1]-1
adjList[src] = append(adjList[src], dst)
adjList[dst] = append(adjList[dst], src)
}
for node, _ := range make([]int, n) {
if !color(node, adjList, colors, visited) {
return false
}
}
return true
}