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 +59
-1
lines changed
Algorithms/0773.sliding-puzzle Expand file tree Collapse file tree 1 file changed +59
-1
lines changed Original file line number Diff line number Diff line change 1
1
package problem0773
2
2
3
+ import (
4
+ "strings"
5
+ )
6
+
3
7
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
+ }
4
57
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 )
6
64
}
You can’t perform that action at this time.
0 commit comments