This repository was archived by the owner on Sep 20, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +16
-15
lines changed
Algorithms/0773.sliding-puzzle Expand file tree Collapse file tree 1 file changed +16
-15
lines changed Original file line number Diff line number Diff line change @@ -5,23 +5,23 @@ import (
5
5
)
6
6
7
7
func slidingPuzzle (board [][]int ) int {
8
- original , target := "123450" , convert (board )
9
- if original == target {
8
+ origin , target := "123450" , convert (board )
9
+ if origin == target {
10
10
return 0
11
11
}
12
12
13
- q := make ([]string , 1 , 720 )
14
- q [0 ] = original
13
+ queue := make ([]string , 1 , 720 )
14
+ queue [0 ] = origin
15
15
16
16
hasSeen := make (map [string ]bool , 720 )
17
- hasSeen [original ] = true
17
+ hasSeen [origin ] = true
18
18
19
- res := 0 // q 中最后一个候选项是 origin 经过 res 次变化得来的
19
+ res := 0
20
20
d := []int {- 1 , 1 , 3 , - 3 }
21
- size := len (q )
22
- for len (q ) > 0 {
23
- //
24
- s := q [0 ]
21
+ countDown := len (queue )
22
+ for len (queue ) > 0 {
23
+ // 从队列中抽取 s 对其进行变形
24
+ s := queue [0 ]
25
25
i := strings .IndexByte (s , '0' )
26
26
for k := range d {
27
27
j := i + d [k ]
@@ -37,15 +37,16 @@ func slidingPuzzle(board [][]int) int {
37
37
}
38
38
39
39
if ! hasSeen [c ] {
40
- q = append (q , c )
40
+ queue = append (queue , c )
41
41
hasSeen [c ] = true
42
42
}
43
43
}
44
44
45
- q = q [1 :]
46
- size --
47
- if size == 0 {
48
- size = len (q )
45
+ // 删除队列头部,检查 res 是否需要 ++
46
+ queue = queue [1 :]
47
+ countDown --
48
+ if countDown == 0 {
49
+ countDown = len (queue )
49
50
res ++
50
51
}
51
52
}
You can’t perform that action at this time.
0 commit comments