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

Commit a4327d8

Browse files
aQuaaQua
authored andcommitted
773 pass
1 parent 27ae49f commit a4327d8

File tree

2 files changed

+35
-26
lines changed

2 files changed

+35
-26
lines changed

Algorithms/0773.sliding-puzzle/sliding-puzzle.go

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,23 @@ import (
55
)
66

77
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"
8+
original, target := "123450", convert(board)
9+
if original == target {
10+
return 0
11+
}
1312

14-
res := 0
13+
q := make([]string, 1, 720)
14+
q[0] = original
1515

16-
if q[0] == target {
17-
return res
18-
}
16+
hasSeen := make(map[string]bool, 720)
17+
hasSeen[original] = true
1918

19+
res := 0 // q 中最后一个候选项是 origin 经过 res 次变化得来的
2020
d := []int{-1, 1, 3, -3}
2121
size := len(q)
2222
for len(q) > 0 {
23+
//
2324
s := q[0]
24-
q = q[1:]
25-
size--
26-
if size == 0 {
27-
size = len(q)
28-
res++
29-
}
3025
i := strings.IndexByte(s, '0')
3126
for k := range d {
3227
j := i + d[k]
@@ -36,12 +31,9 @@ func slidingPuzzle(board [][]int) int {
3631
i == 3 && j == 2 {
3732
continue
3833
}
39-
b := []byte(s)
40-
b[i], b[j] = b[j], b[i]
41-
42-
c := string(b)
34+
c := swap(s, i, j)
4335
if c == target {
44-
return res
36+
return res + 1
4537
}
4638

4739
if !hasSeen[c] {
@@ -50,6 +42,12 @@ func slidingPuzzle(board [][]int) int {
5042
}
5143
}
5244

45+
q = q[1:]
46+
size--
47+
if size == 0 {
48+
size = len(q)
49+
res++
50+
}
5351
}
5452

5553
return -1
@@ -62,3 +60,9 @@ func convert(board [][]int) string {
6260
}
6361
return string(res)
6462
}
63+
64+
func swap(s string, i, j int) string {
65+
b := []byte(s)
66+
b[i], b[j] = b[j], b[i]
67+
return string(b)
68+
}

Algorithms/0773.sliding-puzzle/sliding-puzzle_test.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,29 @@ var tcs = []struct {
1313
ans int
1414
}{
1515

16+
{
17+
[][]int{{4, 1, 2}, {5, 0, 3}},
18+
5,
19+
},
20+
1621
{
1722
[][]int{{1, 2, 3}, {4, 0, 5}},
1823
1,
1924
},
2025

2126
{
22-
[][]int{{1, 2, 3}, {5, 4, 0}},
23-
-1,
27+
[][]int{{3, 2, 4}, {1, 5, 0}},
28+
14,
2429
},
2530

2631
{
27-
[][]int{{4, 1, 2}, {5, 0, 3}},
28-
5,
32+
[][]int{{1, 2, 3}, {4, 5, 0}},
33+
0,
2934
},
3035

3136
{
32-
[][]int{{3, 2, 4}, {1, 5, 0}},
33-
14,
37+
[][]int{{1, 2, 3}, {5, 4, 0}},
38+
-1,
3439
},
3540

3641
// 可以有多个 testcase

0 commit comments

Comments
 (0)