【LeetCode】773. Sliding Puzzle 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/sliding-puzzle/description/
题目描述:
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 1:
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Examples 2:
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Examples 3:
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].
题目大意
这个就是大家都玩过的滑块游戏,有个0表示空格,每次可以把这个空格和其他的一个相邻的位置进行交换。问最后能不能出现第一排第二排依次是"123450"的结局。如果不能,则返回-1;如果可以,需要返回所需要的最少步数。
解题方法
Hard题目真的是一个比一个看起来难,但是只要有充足的经验,能看出这个是考BFS的题目,那么剩下的时间就是套用模板了吧。。
每次移动都相当于得到了一个新的状态,同时记录得到这个状态需要的步数,并把这个状态保存到已经出现过的set里。所以,本题的难点在于使用如果把二维数组和字符串进行转化的问题,代码写的很清楚了,就不详细说了。
需要注意的是,通过二维坐标得到字符串索引的方式是x * cols + y,我觉得应该是常识,可是我第一次没想出来。
Ps,吐槽一句,python的字符画不支持直接指定某个位置的字符,因此这个题里面迫不得已用了几次string和list互转的过程。。
最坏情况下的时间复杂度是O((MN)!),空间复杂度是O(MN)。M,N代表行列数,这个题分别为2,3.
class Solution(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
goal = "123450"
start = self.board2str(board)
bfs = collections.deque()
bfs.append((start, 0))
visited = set()
visited.add(start)
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while bfs:
path, step = bfs.popleft()
if path == goal:
return step
p = path.index("0")
x, y = p / 3, p % 3
path = list(path)
for dir in dirs:
tx, ty = x + dir[0], y + dir[1]
if tx < 0 or tx >= 2 or ty < 0 or ty >= 3:
continue
path[tx * 3 + ty], path[x * 3 + y] = path[x * 3 + y], path[tx * 3 + ty]
pathStr = "".join(path)
if pathStr not in visited:
bfs.append((pathStr, step + 1))
visited.add(pathStr)
path[tx * 3 + ty], path[x * 3 + y] = path[x * 3 + y], path[tx * 3 + ty]
return -1
def board2str(self, board):
bstr = ""
for i in range(2):
for j in range(3):
bstr += str(board[i][j])
return bstr
参考资料:
https://www.youtube.com/watch?v=ABSjW0p3wsM
日期
2018 年 10 月 1 日 —— 欢度国庆!
【LeetCode】773. Sliding Puzzle 解题报告(Python)的更多相关文章
- [LeetCode] 773. 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】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- 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 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
随机推荐
- Scrapy-Splash的安装和使用
Scrapy-Splash是一个Scrapy中支持JavaScript渲染的工具. Scrapy-Splash的安装分为两部分.一个是Splash服务的安装,具体是通过Docker,安装之后,会启动一 ...
- 记一次 .NET 某化妆品 webapi 卡死分析
一:背景 1. 讲故事 10月份星球里的一位老朋友找到我,说他们公司的程序在一个网红直播带货下给弄得无响应了,无响应期间有大量的 RabbitMQ 超时,寻求如何找到根源,聊天截图我就不发了. 既然无 ...
- 巩固javaweb的第三十天
显示用户输入信息 1 .代码 要想输出用户在上一个页面提交的信息,可以使用下面的代码: ${param.userid} ${param.username} ${param.userpass} ${pa ...
- Yarn 生产环境核心配置参数
目录 Yarn 生产环境核心配置参数 ResourceManager NodeManager Container Yarn 生产环境核心配置参数 ResourceManager 配置调度器 yarn. ...
- 理解ASP.NET Core - 模型绑定&验证(Model Binding and Validation)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 模型绑定 什么是模型绑定?简单说就是将HTTP请求参数绑定到程序方法入参上,该变量可以是简单类 ...
- Learning Spark中文版--第三章--RDD编程(1)
本章介绍了Spark用于数据处理的核心抽象概念,具有弹性的分布式数据集(RDD).一个RDD仅仅是一个分布式的元素集合.在Spark中,所有工作都表示为创建新的RDDs.转换现有的RDD,或者调 ...
- 大数据学习day26----hive01----1hive的简介 2 hive的安装(hive的两种连接方式,后台启动,标准输出,错误输出)3. 数据库的基本操作 4. 建表(内部表和外部表的创建以及应用场景,数据导入,学生、分数sql练习)5.分区表 6加载数据的方式
1. hive的简介(具体见文档) Hive是分析处理结构化数据的工具 本质:将hive sql转化成MapReduce程序或者spark程序 Hive处理的数据一般存储在HDFS上,其分析数据底 ...
- Angular @Input讲解及用法
1.什么是@input @input的作用是定义模块输入,是用来让父级组件向子组件传递内容. 2.@input用法 首先在子组件中将需要传递给父组件的变量用@input()修饰 需要在子组件ts文件i ...
- JVM——对象已“死”的判定
主要针对Java堆和方法区 1.判断对象是否已"死" Java堆中存放着几乎所有的对象实例,垃圾回收器在对堆进行回收之前,首先应该判断这些对象哪些还"存活",哪 ...
- linux 6.5 网卡
启动网卡 ifup eth0 eth0:网卡名称 设置网卡开机启动 vi /etc/sysconfig/network-scripts/ifcfg-eth0 ONBOOT=yes