-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path10004.go
79 lines (72 loc) · 1.36 KB
/
10004.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
// UVa 10004 - Bicoloring
package main
import (
"fmt"
"os"
)
func valid(matrix [][]bool, nodes []int, curr, color int) bool {
for i := range matrix[curr] {
if matrix[curr][i] && nodes[i] == color {
return false
}
}
return true
}
func allVisited(nodes []int) bool {
for _, v := range nodes {
if v == 0 {
return false
}
}
return true
}
func dfs(matrix [][]bool, nodes []int, curr, color int) bool {
if allVisited(nodes) {
return true
}
for i := range nodes {
if nodes[i] == 0 {
var nextColor int
if matrix[curr][i] {
nextColor = 3 - color
} else {
nextColor = color
}
if valid(matrix, nodes, i, nextColor) {
nodes[i] = nextColor
if dfs(matrix, nodes, i, nextColor) {
return true
}
nodes[i] = 0
}
}
}
return false
}
func main() {
in, _ := os.Open("10004.in")
defer in.Close()
out, _ := os.Create("10004.out")
defer out.Close()
var n, l, n1, n2 int
for {
if fmt.Fscanf(in, "%d", &n); n == 0 {
break
}
matrix := make([][]bool, n)
for i := range matrix {
matrix[i] = make([]bool, n)
}
for fmt.Fscanf(in, "%d", &l); l > 0; l-- {
fmt.Fscanf(in, "%d%d", &n1, &n2)
matrix[n1][n2], matrix[n2][n1] = true, true
}
nodes := make([]int, n)
nodes[0] = 1
if dfs(matrix, nodes, 0, 1) {
fmt.Fprintln(out, "BICOLORABLE.")
} else {
fmt.Fprintln(out, "NOT BICOLORABLE.")
}
}
}