妙先生


私信TA

用户名:uq_57083779177

访问量:24861

签 名:

妙啊!

等  级
排  名 234
经  验 6002
参赛次数 0
文章发表 73
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:
    很明显用广搜就能解决。


参考代码:

n = int(input())
#模拟地图
mMap = [list(input().split()) for _ in range(n)]
#标记是否访问过、访问过为True未访问过为False
mVis = [[False for _ in range(n)] for _ in range(n) ]
mVis[0][0] = True
#模拟在图中上下左右走
xMove = [-1,1,0,0]
yMove = [0,0,1,-1]
#队列记录坐标和走到的次数
queue = [[0,0,0]]
while queue:
    #当走到了b点退出广搜、打印走的次数
    if mMap[queue[0][0]][queue[0][1]] == 'B':
        print(queue[0][2])
        break
    for i in range(4):
        dx = queue[0][0] + xMove[i]
        dy = queue[0][1] + yMove[i]
        if dx>=0 and dx<=n-1 and dy>=0 and dy<=n-1:
            if not mVis[dx][dy] and mMap[queue[0][0]][queue[0][1]] != mMap[dx][dy]:
                '''没有访问过并且不是连续的走-和+就可以将点加入队列'''
                queue.append([dx,dy,queue[0][2]+1])
                mVis[dx][dy] = True
    queue.pop(0)

if len(queue) == 0:
    """队列为空说明走不到B点"""
    print("-1")


 

0.0分

3 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区