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. c++的boost库

    c++ 的boost库的理解? 参考:http://zh.highscore.de/cpp/boost/introduction.html https://www.cnblogs.com/lidabo ...

  2. c#2.0锐利体验《泛型编程》读书笔记

    1.c#泛型及机制 Class Stack<T> { } T 其实为type的缩小,不过也可为其他字符代替T ,被称为“泛型类型”  T为晚绑定的,在编译的时候还不能确定T的确切类型. 2 ...

  3. IGC(Interleaved Group Convolutions)

    深度学习被引起关注是在2012年,用神经网络训练的一个分类模型在ImagNet上取得了第一名,而且其分类精度比第二名高出10多个点,当时所使用的模型为AlexNet,现在看来其为一个比较简单的网络,而 ...

  4. BZOJ 4764: 弹飞大爷 LCT

    思路并不难,主要是细节需要注意一下. 在 lct 中,删边要写成:f[lson]=0,lson=0 (因为删 x->y 时 y 不一定是左儿子,y 只是 x 的前驱) 然后 f[lson]=ls ...

  5. Python面向对象 -- slots, @property、多重继承MixIn、定制类(str, iter, getitem, getattr, call, callable函数,可调用对象)、元类(type, metaclass)

    面向对象设计中最基础的3个概念:数据封装.继承和多态 动态给class增加功能 正常情况下,当定义了一个class,然后创建了一个class的实例后,可以在程序运行的过程中给该实例绑定任何属性和方法, ...

  6. USACO 2009 Open 干草塔 Tower of Hay

    USACO 2009 Open 干草塔 Tower of Hay Description 为了调整电灯亮度,贝西要用干草包堆出一座塔,然后爬到牛棚顶去把灯泡换掉.干草 包会从传送带上运来,共会出现N包 ...

  7. 基于python的学生管理系统(含数据库版本)

    这次支持连接到后台的数据库,直接和数据库进行交互,实现基本的增删查改 #!/usr/bin/python3 # coding=utf-8 """ ************ ...

  8. 仿站技术——获取和使用某些网站的iconfont图标字体

    前言: 很多前端新手在仿一些大型网站的时候经常遇到一个问题:该网站使用了图标字体——iconfont,虽然现在阿里有开源的iconfont库,但是还是没有原网站的效果(本人强迫症但非处女座).所以此文 ...

  9. docker_基础用法

    1. docker architecture 2. 命令

  10. Nova官方资料入口处

    Nova官方资料地址: https://www.openstack.org/software/releases/queens/components/nova --> https://wiki.o ...