题目描述
解题思路
寻找最少步数,利用BFS算法。构建要跳的步数,以及初始队列进行bfs遍历直到出现满足情况的为止。具体看代买详细注释
代码
from collections import deque
#读入数据
init_state=input()
end_state=input()
#初始化参数
dirct=[1,-1,2,-2,3,-3]#青蛙可移动的参数
state_set={init_state}#记录所有情况,防止重复
q=deque()
q.append((init_state,0))#第一个参数是存当前状态,第二个是步骤数
#bfs
def bfs():
while q:
new_state,pace_numbs=q.popleft()
#青蛙开始跳
for d in dirct:
now_state=list(new_state)#转换成列表
now_pace=pace_numbs
star_index = list(now_state).index('*') # 记录星星的坐标
change_index=star_index+d#记录要与*交换的位置下标
#判断交换下标是否合理
if 0<=change_index<len(now_state) and now_state[change_index]!='*':
now_state[star_index]=now_state[change_index]
now_state[change_index]='*'
now_pace+=1#行动步数加一
if ''.join(now_state)==end_state:#如果交换后等于目标状态,直接输出
print(now_pace)
return
if ''.join(now_state) not in state_set:#如果当前序列没有在之前没出现过
state_set.add(''.join(now_state))
q.append((''.join(now_state),now_pace))
#调用bfs
bfs()