-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path227.go
87 lines (78 loc) · 1.59 KB
/
227.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
80
81
82
83
84
85
86
87
// UVa 227 - Puzzle
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
var directions = map[byte][2]int{'A': {-1, 0}, 'B': {1, 0}, 'R': {0, 1}, 'L': {0, -1}}
func findEmpty(puzzle [][]byte) (int, int) {
for r := range puzzle {
for c := range puzzle[r] {
if puzzle[r][c] == ' ' {
return r, c
}
}
}
return -1, -1
}
func move(puzzle [][]byte, moves string) bool {
r, c := findEmpty(puzzle)
for i := range moves {
direction := directions[moves[i]]
nr, nc := r+direction[0], c+direction[1]
if nr < 0 || nr > 4 || nc < 0 || nc > 4 {
return false
}
puzzle[r][c], puzzle[nr][nc] = puzzle[nr][nc], puzzle[r][c]
r, c = nr, nc
}
return true
}
func output(out io.Writer, puzzle [][]byte) {
for i := range puzzle {
for j := range puzzle[i] {
if j > 0 {
fmt.Fprint(out, " ")
}
fmt.Fprintf(out, "%c", puzzle[i][j])
}
fmt.Fprintln(out)
}
}
func main() {
in, _ := os.Open("227.in")
defer in.Close()
out, _ := os.Create("227.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
var line string
here:
for kase := 1; ; kase++ {
puzzle := make([][]byte, 5)
for i := 0; i < 5 && s.Scan(); i++ {
if line = s.Text(); i == 0 && line == "Z" {
break here
}
puzzle[i] = []byte(line)
}
var moves string
for s.Scan() {
if moves += s.Text(); strings.HasSuffix(moves, "0") {
break
}
}
if kase > 1 {
fmt.Fprintln(out)
}
fmt.Fprintf(out, "Puzzle #%d:\n", kase)
if move(puzzle, moves[:len(moves)-1]) {
output(out, puzzle)
} else {
fmt.Fprintln(out, "This puzzle has no final configuration.")
}
}
}