-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path677.go
70 lines (63 loc) · 1.18 KB
/
677.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
// UVa 677 - All Walks of length "n" from the first node
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
var (
paths []string
n int
matrix [][]bool
visited map[int]bool
)
func dfs(curr, level int, path []string) {
if level == n {
paths = append(paths, "("+strings.Join(path, ",")+")")
return
}
for i, v := range matrix[curr] {
if v && !visited[i] {
visited[i] = true
dfs(i, level+1, append(path, strconv.Itoa(i+1)))
visited[i] = false
}
}
}
func solve() string {
paths = nil
visited = map[int]bool{0: true}
dfs(0, 0, []string{"1"})
return strings.Join(paths, "\n")
}
func main() {
in, _ := os.Open("677.in")
defer in.Close()
out, _ := os.Create("677.out")
defer out.Close()
var m, tmp int
for first := true; ; {
if _, err := fmt.Fscanf(in, "%d%d", &m, &n); err != nil {
break
}
matrix = make([][]bool, m)
for i := range matrix {
matrix[i] = make([]bool, m)
}
for i := range matrix {
for j := range matrix[i] {
if fmt.Fscanf(in, "%d", &tmp); tmp == 1 {
matrix[i][j] = true
}
}
}
fmt.Fscanf(in, "%d", &tmp)
if first {
first = false
} else {
fmt.Fprintln(out)
}
fmt.Fprintln(out, solve())
}
}