Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 27ae49f

Browse files
aQuaaQua
authored andcommitted
773 wrong answer
1 parent d8db7f2 commit 27ae49f

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed
Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,64 @@
11
package problem0773
22

3+
import (
4+
"strings"
5+
)
6+
37
func slidingPuzzle(board [][]int) int {
8+
hasSeen := make(map[string]bool, 720)
9+
q := make([]string, 1, 720)
10+
q[0] = convert(board)
11+
hasSeen[q[0]] = true
12+
target := "123450"
13+
14+
res := 0
15+
16+
if q[0] == target {
17+
return res
18+
}
19+
20+
d := []int{-1, 1, 3, -3}
21+
size := len(q)
22+
for len(q) > 0 {
23+
s := q[0]
24+
q = q[1:]
25+
size--
26+
if size == 0 {
27+
size = len(q)
28+
res++
29+
}
30+
i := strings.IndexByte(s, '0')
31+
for k := range d {
32+
j := i + d[k]
33+
if j < 0 ||
34+
j > 5 ||
35+
i == 2 && j == 3 ||
36+
i == 3 && j == 2 {
37+
continue
38+
}
39+
b := []byte(s)
40+
b[i], b[j] = b[j], b[i]
41+
42+
c := string(b)
43+
if c == target {
44+
return res
45+
}
46+
47+
if !hasSeen[c] {
48+
q = append(q, c)
49+
hasSeen[c] = true
50+
}
51+
}
52+
53+
}
54+
55+
return -1
56+
}
457

5-
return 0
58+
func convert(board [][]int) string {
59+
res := make([]byte, 6)
60+
for i := range res {
61+
res[i] = byte(board[i/3][i%3]) + '0'
62+
}
63+
return string(res)
664
}

0 commit comments

Comments
 (0)