-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path429.go
78 lines (70 loc) · 1.37 KB
/
429.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
// UVa 429 - Word Transformation
package main
import (
"fmt"
"os"
)
func sameLenAndOneCharDiff(w1, w2 string) bool {
if len(w1) != len(w2) {
return false
}
count := 0
for i := range w1 {
if w1[i] != w2[i] {
count++
}
}
return count == 1
}
func buildLink(dict map[string][]string, word string) {
dict[word] = nil
for k, v := range dict {
if k != word && sameLenAndOneCharDiff(k, word) {
dict[k] = append(v, word)
dict[word] = append(dict[word], k)
}
}
}
type node struct {
w string
n int
}
func bfs(dict map[string][]string, fm, to string) int {
for visited, queue := map[string]bool{fm: true}, []node{{fm, 0}}; len(queue) > 0; queue = queue[1:] {
curr := queue[0]
adjs := dict[curr.w]
for _, v := range adjs {
if v == to {
return curr.n + 1
}
if _, ok := visited[v]; !ok {
visited[v] = true
queue = append(queue, node{v, curr.n + 1})
}
}
}
return -1
}
func main() {
in, _ := os.Open("429.in")
defer in.Close()
out, _ := os.Create("429.out")
defer out.Close()
var n int
var word, fm, to string
for fmt.Fscanf(in, "%d\n\n", &n); n > 0; n-- {
dict := make(map[string][]string)
for {
if fmt.Fscanf(in, "%s", &word); word == "*" {
break
}
buildLink(dict, word)
}
for {
if _, err := fmt.Fscanf(in, "%s%s\n", &fm, &to); err != nil {
break
}
fmt.Fprintln(out, fm, to, bfs(dict, fm, to))
}
}
}