[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:
board
will 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 ...
随机推荐
- Python 爬虫js加密破解(四) 360云盘登录password加密
登录链接:https://yunpan.360.cn/mindex/login 这是一个md5 加密算法,直接使用 md5加密即可实现 本文讲解的是如何抠出js,运行代码 第一部:抓包 如图 第二步: ...
- app安全测试初级
分析方法:静态分析 主要是利用apktool.dex2jar.jd-gui.smali2dex等静态分析工具对应用进行反编译,并对反编译后的java文件.xml文件等文件进行静态扫描分析,通过关键词搜 ...
- Python应用之-file 方法
#!/usr/bin/env python # *_* coding=utf-8 *_* """ desc: 文件方法 ######################### ...
- POJ - 3728:The merchant (Tarjan 带权并查集)
题意:给定一个N个节点的树,1<=N<=50000 每个节点都有一个权值,代表商品在这个节点的价格.商人从某个节点a移动到节点b,且只能购买并出售一次商品,问最多可以产生多大的利润. 思路 ...
- AtCoder Beginner Contest 126 解题报告
突然6道题.有点慌.比赛写了五个.罚时爆炸.最后一个时间不太够+没敢写就放弃了. 两道题奇奇怪怪的WJ和20/20.今天的评测机是怎么了. A Changing a Character #includ ...
- Scanner的常用用法
通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所输入的内容传给Scanner. s.useDelimiter(" |,|\ ...
- xrange和range的区别?
range: 函数说明,range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个列表. xrange:函数说明,xrange 用法与 ...
- python 报can't subtract offset-naive and offset-aware datetimes错误
两个时间一个含时区,一个不含时区
- 洛谷 P2813【母舰】 题解
总体思路: 输入护盾和攻击力,然后快速排序sort走起来, 排完序之后从第一个开始找,如果攻击力大于护盾,护盾继续下一个, 这个攻击力记录为0,如果小雨的话,那就攻击力继续下一个,护盾不动, 其中最为 ...
- 64、Spark Streaming:StreamingContext初始化与Receiver启动原理剖析与源码分析
一.StreamingContext源码分析 ###入口 org.apache.spark.streaming/StreamingContext.scala /** * 在创建和完成StreamCon ...