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

解法2: A* Search
Java:
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();
}    
Python: A* Search
    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  
Python:
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 滑动拼图的更多相关文章

  1. [LeetCode] Sliding Puzzle 滑动拼图

    On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square repre ...

  2. LeetCode 773. Sliding Puzzle

    原题链接在这里:https://leetcode.com/problems/sliding-puzzle/description/ 题目: On a 2x3 board, there are 5 ti ...

  3. 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的值. 最 ...

  4. 【LeetCode】773. Sliding Puzzle 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/sliding- ...

  5. 【leetcode】Sliding Puzzle

    题目如下: On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square ...

  6. Leetcode之广度优先搜索(BFS)专题-773. 滑动谜题(Sliding Puzzle)

    Leetcode之广度优先搜索(BFS)专题-773. 滑动谜题(Sliding Puzzle) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary ...

  7. python 游戏(滑动拼图Slide_Puzzle)

    1. 游戏功能和流程图 实现16宫格滑动拼图,实现3个按钮(重置用户操作,重新开始游戏,解密游戏),后续难度,额外添加重置一次的按钮,解密算法的植入,数字改变为图片植入 游戏流程图 2. 游戏配置 配 ...

  8. 鸿蒙第三方组件——SwipeCaptcha滑动拼图验证组件

    目录:1.组件效果展示2.Sample解析3.<鸿蒙第三方组件>系列文章合集 前言 基于安卓平台的滑动拼图验证组件SwipeCaptcha( https://github.com/mcxt ...

  9. 原生js+canvas实现滑动拼图验证码

    上图为网易云盾的滑动拼图验证码,其应该有一个专门的图片库,裁剪的位置是固定的.我的想法是,随机生成图片,随机生成位置,再用canvas裁剪出滑块和背景图.下面介绍具体步骤. 首先随便找一张图片渲染到c ...

随机推荐

  1. Dynamics 365 On-premises和Online 的不同

    1.新建账号的不同:on-premises(下文简称op)是和ad绑定的,所以必须先在ad中新建账号后才能在CRM中新建.而online是和Office365(下文简称O365)绑定的,所以需在O36 ...

  2. janusgraph-图数据库的学习(1)

    图数据库的简介-来源百度百科 1.简介 图形数据库是NoSQL数据库的一种类型,它应用图形理论存储实体之间的关系信息.图形数据库是一种非关系型数据库,它应用图形理论存储实体之间的关系信息.最常见例子就 ...

  3. linux 读取文件

    linux读取文件是经常要用到的操作,以下示例(说明看注释): #读取文件snlist.txt中的每一行内容赋给sn变量 while read sn do echo ">>> ...

  4. mac系统下 PHPStorm 快捷键

    PHPStorm可以自己设置快捷键 按住command + , 打开Preferences点击Keymap,右边出现下拉框点击下拉框选择你想要的快捷键设置,eclipse快捷键比较常用 eclipse ...

  5. linux date获取时间戳

    linux 时间戳格式 年月日 时分秒: `date ‘+%Y%m%d%H%M%S’`date +%Y%m%d%H%M%S // 年月日 时分秒date +%s // 从 1970年1月1日零点开始到 ...

  6. linux命令之------Linux文档编辑

    1.Vi和vim三种模式 (1)命令模式:移动光标 (2)插入模式:编辑文档 (3)末行模式:保存退出 不同模式操作示意图: 其中wq是保存退出,wq!强制保存退出:q不保存退出:q!强制不保存退出. ...

  7. java内存dump文件导出与查看

    生成dump文件的命令:jmap -dump:format=b,file=20170307.dump 16048file后面的是自定义的文件名,最后的数字是进程的pid 使用jvisualvm来分析d ...

  8. hosts 屏蔽定位域名

    通过修改hosts屏蔽定位服务的域名 #屏蔽百度地图 1.0.0.1 api.map.baidu.com 1.0.0.1 ps.map.baidu.com 1.0.0.1 sv.map.baidu.c ...

  9. ssm框架中,项目启动过程以及web.xml配置详解

    原文:https://blog.csdn.net/qq_35571554/article/details/82385838 本篇主要在基于SSM的框架,深入讲解web.xml的配置 web.xml   ...

  10. hadoop综合

    对CSV文件进行预处理生成无标题文本文件,将爬虫大作业产生的csv文件上传到HDFS 首先,我们需要在本地中创建一个/usr/local/bigdatacase/dataset文件夹,具体的步骤为: ...