九宫重排
题目描述
如下图的九宫格中,放着 1 ~ 8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。 经过若干次移动,可以形成图 2 所示的局面。
我们把上图的局面记为:12345678.
把下图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出 -1。
思路
典型的bfs(宽度优先搜索)就是在判断边界条件的时候要注意一下,移动位置上下加减三,左右加减一
代码实现
import sys
from collections import deque
start = input()
end = input()
q = deque()
q.append((start,0)) #加入起始数据,移动次数
dic = set()
dic.add(start) #去重
dir = [1,-1,3,-3] #九宫格移动方向
while q: #非空就运行
now = q.popleft() #双端队列 头部删除
for i in dir: #四个位置
state = list(now[0]) #读出队列当前的字符串,转换为数组
count = now[1] #次数
index = state.index('.') #找.的索引位置
new_index = index + i #索引的新位置
if new_index >= 0 and new_index < 9 and (index == 2 and new_index == 3) == 0 and (index == 3 and new_index == 2) == 0 and (index == 5 and new_index == 6) == 0 and (
index == 6 and new_index == 5) == 0: #防止越界
state[index], state[new_index] = state[new_index], state[index] #换位
end_index = ''.join(state)
count += 1
if end_index == end: #判断退出条件
print(count)
sys.exit(0) #直接结束程序
if end_index not in dic: #去重
q.append((end_index,count))
dic.add(end_index)
输入
12345678.
123.46758
输出
3