[LeetCode] 773. Sliding Puzzle 滑动拼图
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given a puzzle board, return the least number of moves required so that 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: 1
Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 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:
boardwill be a 2 x 3 array as described above.board[i][j]will be a permutation of[0, 1, 2, 3, 4, 5].
给定2行3列的矩阵board,包含数字0 - 5,求将其恢复为[[1,2,3],[4,5,0]]的状态最少需要移动多少次。
拼图问题,其实就是八数码问题,给定一个可移动的数字,该数字每次只能朝四个方向移动,问最少经过多少次移动能够完成拼图(给定的序列)。刚开始看到的时候完全没思路,后来想到了用BFS来解,BFS相当于一种暴力搜索,每次去搜索所有可能的结果(对本题来说就是三个方向),直到满足条件或退出。事实上看了一些博客了解到更好的解法是A*,这里先不考虑A*,在后面的寻路算法的实现中会写A*的实现。关于BFS的实现,自我感觉自己的写法应该是比较优秀的写法,相对于网上的很多实现来讲,更加简洁,也符合C++的标准。
解法:BFS
public int slidingPuzzle(int[][] board) {
Set<String> seen = new HashSet<>(); // used to avoid duplicates
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()) { // Not 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 be 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, has to use size control here, otherwise not needed
int size = 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();
}
def slidingPuzzle(self, board):
self.goal = [[1,2,3], [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)
return 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
class Solution(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
step = 0
board = tuple(map(tuple, board))
q = [board]
memo = set([board])
while q:
q0 = []
for b in q:
if b == ((1,2,3), (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 heapq
import itertools # A* Search Algorithm
class 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(board), 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) for j in xrange(C)} min_steps = heuristic_estimate(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:
new_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_closer = 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)!)
# A* Search Algorithm
class 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) for 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 > lookup[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], tmp[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.size(), 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.front().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;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 773. Sliding Puzzle 滑动拼图的更多相关文章
- [LeetCode] Sliding Puzzle 滑动拼图
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square repre ...
- LeetCode 773. Sliding Puzzle
原题链接在这里:https://leetcode.com/problems/sliding-puzzle/description/ 题目: On a 2x3 board, there are 5 ti ...
- leetcode 542. 01 Matrix 、663. Walls and Gates(lintcode) 、773. Sliding Puzzle 、803. Shortest Distance from All Buildings
542. 01 Matrix https://www.cnblogs.com/grandyang/p/6602288.html 将所有的1置为INT_MAX,然后用所有的0去更新原本位置为1的值. 最 ...
- 【LeetCode】773. Sliding Puzzle 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/sliding- ...
- 【leetcode】Sliding Puzzle
题目如下: On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square ...
- Leetcode之广度优先搜索(BFS)专题-773. 滑动谜题(Sliding Puzzle)
Leetcode之广度优先搜索(BFS)专题-773. 滑动谜题(Sliding Puzzle) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary ...
- python 游戏(滑动拼图Slide_Puzzle)
1. 游戏功能和流程图 实现16宫格滑动拼图,实现3个按钮(重置用户操作,重新开始游戏,解密游戏),后续难度,额外添加重置一次的按钮,解密算法的植入,数字改变为图片植入 游戏流程图 2. 游戏配置 配 ...
- 鸿蒙第三方组件——SwipeCaptcha滑动拼图验证组件
目录:1.组件效果展示2.Sample解析3.<鸿蒙第三方组件>系列文章合集 前言 基于安卓平台的滑动拼图验证组件SwipeCaptcha( https://github.com/mcxt ...
- 原生js+canvas实现滑动拼图验证码
上图为网易云盾的滑动拼图验证码,其应该有一个专门的图片库,裁剪的位置是固定的.我的想法是,随机生成图片,随机生成位置,再用canvas裁剪出滑块和背景图.下面介绍具体步骤. 首先随便找一张图片渲染到c ...
随机推荐
- 逆向破解之160个CrackMe —— 006
CrackMe —— 006 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...
- 我感觉这个书上的微信小程序登陆写得不好
基本功能是OK,但是感觉传的数据太多,不安全,需要改写. App({ d: { hostUrl: 'http://www.test.com/index.php', //请填写您自己的小程序主机URL ...
- ASP.NET Core 类库中取读配置文件 appsettings.json
首先引用NuGet包 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json Microsoft.Exte ...
- LGOJP1850 换教室
题目地址 https://www.luogu.org/problem/P1850 题解 这题的转移其实挺好想的但是方程特别长...真的特别长... 首先设\(f[i,j,0/1]\)表示当前在第\(i ...
- VMware共享本地文件
最后可以在这里找到
- pandas 筛选
t={ , , np.nan, , np.nan, ], "city": ["BeiJing", "ShangHai", "Gua ...
- janusgraph-mgmt中的一些操作
关闭事务 mgmt = graph.openManagement(); ids = mgmt.getOpenInstances(); for(String id : ids){if(!id.conta ...
- Making Huge Palindromes LightOJ - 1258
题目链接:LightOJ - 1258 1258 - Making Huge Palindromes PDF (English) Statistics Forum Time Limit: 1 se ...
- codeforcesC - Berry Jam(折半枚举+1-1序列前后缀和)
Educational Codeforces Round 78 (Rated for Div. 2) C - Berry Jam C. Berry Jam time limit per test 2 ...
- 如何调试 Windows 服务
概要 本文分步介绍了如何使用 WinDbg 调试程序 (windbg.exe) 调试 Windows 服务. 要调试 Windows 服务,可以在服务启动后将 WinDbg 调试程序附加到托管该服务的 ...