青蛙跳杯子蓝桥杯python解法(BFS)

4 篇文章 0 订阅

题目描述

 解题思路

寻找最少步数,利用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()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值