On a 2x3 board
, there is 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.
A move consists of choosing and 0
a 4-directionally adjacent number and swapping it.
The state of the board are solved if and only if the IS board
[[1,2,3],[4,5,0]].
Given a puzzle board, return the least number of moves required so then the state of the board is solved. If It is impossible for the state of the board to be solved, return-1.
Examples:
Input:board = [[1,2,3],[4,0,5]]output:1explanation:swap the 0 and the 5 in one move.
Input:board = [[1,2,3],[5,4,0]]output: -1explanation:no number of moves would make the board solved.
Input:board = [[4,1,2],[5,0,3]]output:5explanation:5 is the smallest number of moves that solves the board. An example path:after move 0: [[4,1,2],[5,0,3]]after Move 1: [[4,1,2],[0,5,3]]after Move 2: [[0,1,2],[4,5,3]]after Move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]]after Move 5: [[1,2,3],[4,5,0]]
Input:board = [[3,2,4],[1,5,0]]output:14
Note:
board
would be a 2 x 3 array as described above.
board[i][j]
Would be a permutation of [0, 1, 2, 3, 4, 5]
.
Given the matrix Board of 2 rows and 3 columns, contains the number 0-5, which requires the minimum number of times to move it back to the state of [[1,2,3],[4,5,0]].
Puzzle problem, is actually eight digital problem, given a movable number, the number can only move in four directions at a time, ask at least how many times the movement can complete the puzzle (given sequence). Just beginning to see the time completely no idea, then thought of using BFS to solve, BFS equivalent to a violent search, every time to search for all possible results (for the subject is three directions), until the condition or exit. In fact, read some blogs understand that a better solution is a *, where a * is not considered first, in the following implementation of the pathfinding algorithm will write a * implementation. About the implementation of BFS, the self-feeling of their own writing should be relatively good writing, compared to many of the online implementation, more concise, also in line with C + + standards.
Solution: BFS Solution 2:a* Searchjava:
public int Slidingpuzzle (int[][] board) {set<string> seen = new hashset<> ();//used to avoid duplicat Es String target = "123450"; Convert board to string-initial state. String s = arrays.deeptostring (board). ReplaceAll ("\\[|\\]|,|\\s", "" "); queue<string> q = new linkedlist<> (arrays.aslist (s)); Seen.add (s); Add initial state to set. int ans = 0; Record the # of rounds of breadth Search while (!q.isempty ()) {//Don't traverse all states yet? Loop used to control search breadth. for (int sz = Q.size (), sz > 0;--sz) {String str = q.poll (); if (str.equals (target)) {return ans;}//Found target. int i = Str.indexof (' 0 '); Locate ' 0 ' int[] D = {1,-1, 3,-3}; Potential swap displacements. for (int k = 0, K < 4; ++k) {//Traverse all options. Int J = i + d[k]; PotenTial Swap index. Conditional used to avoid invalid swaps. if (J < 0 | | J > 5 | | i = 2 && j = = 3 | | i = = 3 && j = 2) {continue;} char[] ch = str.tochararray (); Swap ch[i] and ch[j]. char tmp = ch[i]; Ch[i] = Ch[j]; CH[J] = tmp; s = string.valueof (CH); A new candidate state. if (Seen.add (s)) {Q.offer (s);}//avoid duplicate. }} ++ans; Finished a round of breadth Search, plus 1. } return-1; }
Java:
public int Slidingpuzzle (int[][] board) {String target = "123450"; String start = ""; for (int i = 0, i < board.length; i++) {for (int j = 0; J < Board[0].length; J + +) {Start + = Board[i][j]; }} hashset<string> visited = new hashset<> (); All the positions 0 can is swapped to int[][] dirs = new int[][] {{1, 3}, {0, 2, 4}, {1, 5 }, {0, 4}, {1, 3, 5}, {2, 4}}; queue<string> queue = new linkedlist<> (); Queue.offer (start); Visited.add (start); int res = 0; while (!queue.isempty ()) {//Level count, have to use the size control here, otherwise not needed int si Ze = queue.size (); for (int i = 0; i < size; i++) {String cur = queue.poll (); if (cur.equals (target)) {return res; } int zero = Cur.indexof (' 0 '); Swap if possible for (int Dir:dirs[zero]) {String next = swap (cur, zero, dir); if (Visited.contains (next)) {continue; } visited.add (next); Queue.offer (next); }} res++; } return-1; } private string Swap (string str, int i, int j) {StringBuilder sb = new StringBuilder (str); Sb.setcharat (I, Str.charat (j)); Sb.setcharat (J, Str.charat (i)); return sb.tostring (); }
python:a* Search
def slidingpuzzle (self, board): Self.goal = [[], [4,5,0]] Self.score = [0] * 6 self.score[0] = [[3, 2, 1], [2, 1, 0]] self.score[1] = [[0, 1, 2], [1, 2, 3]] self.score[2] = [[1, 0, 1], [2, 1, 2]] SELF.SCORE[3] = [[2, 1, 0], [3, 2, 1]] self.score[4] = [[1, 2, 3], [0, 1, 2]] self.score[5] = [[2, 1, 2], [1, 0, 1] heap = [(0, 0, board)] closed = [] while Len (heap) > 0:node = Heapq.heappop (heap) If node[2] = = Self.goal:return Node[1] elif node[2] in closed:continue Else:for Next in Self.get_neighbors (Node[2]): If Next in Closed:continue Heapq.heappush (Heap, (node[1] + 1 + self.get_score (next), node[1] + 1, Next)) Closed.append (node[2]) Return-1 def get_neighbors (self, board): res = [] if 0 in board[0]: r, C = 0, board[0]. Index(0) Else:r, c = 1, board[1].index (0) for OFFR, OFFC in [[0, 1], [0,-1], [1, 0], [-1, 0]]: If 0 <= r + OFFR < 2 and 0 <= C + OFFC < 3:board1 = copy.deepcopy (board) BOARD1[R][C], BOARD1[R+OFFR][C+OFFC] = BOARD1[R+OFFR][C+OFFC], Board1[r][c] Res.append (board1) retur n Res def get_score (self, board): score = 0 for I in range (2): for J in Range (3): Score + = Self.score[board[i][j]][i][j] Return score
Python:
Class solution (Object): Def slidingpuzzle (self, Board): "" ": Type Board:list[list[int]]: rtype:i NT "" "Step = 0 board = tuple (map (tuple, board)) q = [board] memo = set ([board]) While q:q0 = [] for b in q:if b = = ((), (4,5,0)): Return step For x in range (2): For y in range (3): If B[x][y]: Continue For dx, dy in zip ((1, 0,-1, 0), (0, 1, 0,-1)): NX, NY = x + dx, y + dy If 0 <= NX < 2 and 0 <= ny < 3:NB = List (map (list, b)) Nb[nx][ny], nb[x][y] = Nb[x][y], Nb[nx][ny] nb = tuple (map (tuple, NB)) If NB not in Memo:memo.add (NB) Q0.append (NB) Q = q0 Step + = 1 return-1
Python:
# Time:o ((M * N) * (M * n)!) # Space:o ((M * N) * (M * n)!) Import Heapqimport itertools# * Search Algorithmclass Solution (object): Def slidingpuzzle (self, Board): "" " : Type Board:list[list[int]]: Rtype:int "" "Def Dot (P1, p2): return p1[0]*p2[0]+p1[1] *P2[1] def heuristic_estimate (board, R, C, expected): result = 0 for I in Xrange (r): For j in Xrange (C): val = board[c*i + j] if val = = 0:continue R, C = expected[val] result + = ABS (r-i) + ABS (C-J) return result r, C = Len (boar D), Len (board[0]) begin = Tuple (Itertools.chain (*board)) end = Tuple (range (1, r*c) + [0]) expected = {(c*i+j+1)% (r*c): (i, J) for I in Xrange (R) to J in Xrange (C)} min_steps = Heuristic_estimat E (Begin, R, C, expected) closer, Detour = [(Begin.index (0), begin)], []Lookup = set () while true:if not closer:if not detour:return-1 Min_steps + = 2 Closer, Detour = Detour, closer zero, board = Closer.pop () If board = = End:return min_steps If board not in Lookup:lookup.add (board) R, C = Divmod (zero, c) for direction in (( -1, 0), (1, 0), (0,-1), (0, 1)): I , j = r+direction[0], c+direction[1] if 0 <= i < r and 0 <= J < c:n Ew_zero = i*c+j tmp = List (board) Tmp[zero], Tmp[new_zero] = Tmp[new_zero], Tmp[zero] New_board = tuple (TMP) r2, c2 = Expected[board[new_zero]] R1, C1 = Divmod (zero, c) r0, C0 = Divmod (New_zero, c) is_clos ER = dot ((r1-r0, c1-c0), (R2-r0, C2-C0)) > 0 (Closer if is_closer else Detour). Append ((New_zero, New_board)) return min_steps
Python:
# Time:o ((M * N) * (M * n)! * LOG ((M * n)!)) # Space:o ((M * N) * (M * n)!) # * Search algorithmclass Solution2 (object): Def slidingpuzzle (self, Board): "" ": Type board:list[list[ INT]]: Rtype:int "" "Def heuristic_estimate (board, R, C, expected): result = 0 For I in Xrange (R): for J in Xrange (C): val = board[c*i + j] if Val = = 0:continue R, c = expected[val] result + = ABS (r-i) + ABS (C-J) return Result R, C = Len (board), Len (board[0]) begin = Tuple (Itertools.chain (*board)) end = Tuple (range (1, R *C) + [0]) End_wrong = tuple (range (1, r*c-2) + [r*c-1, r*c-2, 0]) expected = {(c*i+j+1)% (r*c): (i, J) For I in Xrange (R) to J in Xrange (C)} min_heap = [(0, 0, begin.index (0), begin)] Lookup = { begin:0} while Min_heap:f, G, zero, board = HEAPQ.Heappop (min_heap) If board = = End:return g If board = end_wrong:return-1 if f > Lo Okup[board]: Continue r, C = Divmod (zero, c) for direction in ((-1, 0), (1, 0), (0,-1), (0, 1)): I, j = r+direction[0], c+direction[1] if 0 <= i < r and 0 <= J < c: New_zero = c*i+j tmp = List (board) Tmp[zero], Tmp[new_zero] = Tmp[new_zero], TM P[zero] New_board = tuple (tmp) F = g+1+heuristic_estimate (New_board, R, C, expected) If f < lookup.get (New_board, float ("INF")): Lookup[new_board] = f Heapq.heappush (Min_heap, (f, g+1, New_zero, New_board)) return-1
C + +:
Class Solution {Public:int slidingpuzzle (vector<vector<int>>& board) {int res = 0, M = Board.s Ize (), n = board[0].size (); String target = "123450", start = ""; Vector<vector<int>> dirs{{1,3}, {0,2,4}, {1,5}, {0,4}, {1,3,5}, {2,4}}; for (int i = 0, i < m; ++i) {for (int j = 0; J < N; ++j) {Start + = to_string (Board[i][j] ); }} unordered_set<string> Visited{start}; Queue<string> Q{{start}}; while (!q.empty ()) {for (int i = Q.size ()-1; I >= 0; i.) {String cur = Q.front (); Q.pop ( ); if (cur = = target) return res; int zero_idx = Cur.find ("0"); for (int dir:dirs[zero_idx]) {string cand = cur; Swap (Cand[dir], cand[zero_idx]); if (Visited.count (cand)) continue; Visited.insert (cand); Q.push (cand); }} ++res; } return-1; }};
C + +:
Class Solution {Public:int slidingpuzzle (vector<vector<int>>& board) {int res = 0; Set<vector<vector<int>>> visited; Queue<pair<vector<vector<int>> vector<int>>> q; Vector<vector<int>> Correct{{1, 2, 3}, {4, 5, 0}}; Vector<vector<int>> dirs{{0,-1}, {-1, 0}, {0, 1}, {1, 0}}; for (int i = 0, i < 2; ++i) {for (int j = 0; j < 3; ++j) {if (board[i][j] = = 0) Q.push ({ Board, {i, J}}); }} while (!q.empty ()) {for (int i = Q.size ()-1; I >= 0; i) {Auto T = q.f Ront (). First; Auto zero = Q.front (). Second; Q.pop (); if (t = = correct) return res; Visited.insert (t); for (auto dir:dirs) {int x = zero[0] + dir[0], y = zero[1] + dir[1]; if (x < 0 | | x >= 2 | | y < 0 | | y>= 3) Continue; vector<vector<int>> cand = t; Swap (cand[zero[0]][zero[1]], cand[x][y]); if (Visited.count (cand)) continue; Q.push ({cand, {x, y}}); }} ++res; } return-1; }};
[Leetcode] 773. Sliding Puzzle Sliding Puzzle