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
| func slidingPuzzle(board [][]int) int { target := "123450" neighbor := [][]int{ {1, 3}, {0, 4, 2}, {1, 5}, {0, 4}, {3, 1, 5}, {4, 2}, }
sb := strings.Builder{} for _, i := range board { for _, v := range i { sb.WriteString(strconv.Itoa(v)) } } start := sb.String()
queue := make([]string, 0) visited := make(map[string]bool)
queue = append(queue, start) visited[start] = true
steps := 0 for len(queue) != 0 { sz := len(queue) for i := 0; i < sz; i++ { currState := queue[0] queue = queue[1:]
if currState == target { return steps }
zeroIdx := 0 for i, c := range currState { if c == '0' { zeroIdx = i break } }
for _, n := range neighbor[zeroIdx] { newState := moveZero(currState, zeroIdx, n) if _, ok := visited[newState]; !ok { queue = append(queue, newState) visited[newState] = true } } } steps++ } return -1 }
func moveZero(state string, from, to int) string { chars := []rune(state) chars[from], chars[to] = chars[to], chars[from] return string(chars) }
|