-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path567.go
58 lines (51 loc) · 1.1 KB
/
567.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
// UVa 567 - Risk
package main
import (
"fmt"
"os"
)
const n = 20
type node struct{ n, step int }
func bfs(n1, n2 int, matrix [][]bool) int {
for queue := []node{{n1, 0}}; len(queue) > 0; queue = queue[1:] {
curr := queue[0]
for i := 1; i <= n; i++ {
if matrix[curr.n][i] {
if i == n2 {
return curr.step + 1
}
queue = append(queue, node{i, curr.step + 1})
}
}
}
return -1
}
func main() {
in, _ := os.Open("567.in")
defer in.Close()
out, _ := os.Create("567.out")
defer out.Close()
var cnt, tmp, kase, n1, n2 int
for set := 1; ; set++ {
matrix := make([][]bool, n+1)
for i := range matrix {
matrix[i] = make([]bool, n+1)
}
for i := 1; i < n; i++ {
if _, err := fmt.Fscanf(in, "%d", &cnt); err != nil {
return
}
for ; cnt > 0; cnt-- {
fmt.Fscanf(in, "%d", &tmp)
matrix[i][tmp] = true
matrix[tmp][i] = true
}
}
fmt.Fprintf(out, "Test Set #%d\n", set)
for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- {
fmt.Fscanf(in, "%d%d", &n1, &n2)
fmt.Fprintf(out, "%2d to %2d: %d\n", n1, n2, bfs(n1, n2, matrix))
}
fmt.Fprintln(out)
}
}