D


私信TA

用户名:ALS1111

访问量:19512

签 名:

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

  自我简介:

TA的其他文章

python-摆花摆花
浏览:119

解题思路:

深度搜索。

①定位A点的坐标

②开始搜索,依次搜索上下左右是否能走,若能,则走。

③直到找到B,判断所用步长是否最小,若是,更新最小值。



注意事项:

参考代码:

from cmath import inf  
  
def dfs(x,y,space):  
    global n  
    global Graph  
    global sign  
    global minspace  
  
    if Graph[x][y] == 'B':       #判断是否到大B点,若到达,判断所用步长是否最小
        if space < minspace:  
            minspace = space  
        return  
      
    temp = Graph[x][y]        #记录这一位置的符号  
    if temp == 'A':  
        if 0<=x-1<=n-1 and 0<=y<=n-1 and sign[x-1][y]:  
            sign[x-1][y] = 0    #此处要进行标记,已经走过
            dfs(x-1,y,space+1)  
            sign[x-1][y] = 1    #注意!!!不要忘记进行搜索之后将这一点走过的标记抹除,不然这点只能走一次
        if 0<=x+1<=n-1 and 0<=y<=n-1 and sign[x+1][y]:  
            sign[x+1][y] = 0  
            dfs(x+1,y,space+1)  
            sign[x+1][y] = 1  
        if 0<=x<=n-1 and 0<=y-1<=n-1 and sign[x][y-1]:  
            sign[x][y-1] = 0  
            dfs(x,y-1,space+1)  
            sign[x][y-1] = 1  
        if 0<=x<=n-1 and 0<=y+1<=n-1 and sign[x][y+1]:  
            sign[x][y+1] = 0  
            dfs(x,y+1,space+1)   
            sign[x][y+1] = 1  
    else:  
        if 0<=x-1<=n-1 and 0<=y<=n-1 and Graph[x-1][y] != temp and sign[x-1][y]:  
            sign[x-1][y] = 0  
            dfs(x-1,y,space+1)  
            sign[x-1][y] = 1  
        if 0<=x+1<=n-1 and 0<=y<=n-1 and Graph[x+1][y] != temp and sign[x+1][y]:  
            sign[x+1][y] = 0  
            dfs(x+1,y,space+1)  
            sign[x+1][y] = 1  
        if 0<=x<=n-1 and 0<=y-1<=n-1 and Graph[x][y-1] != temp and sign[x][y-1]:  
            sign[x][y-1] = 0  
            dfs(x,y-1,space+1)  
            sign[x][y-1] = 1  
        if 0<=x<=n-1 and 0<=y+1<=n-1 and Graph[x][y+1] != temp and sign[x][y+1]:  
            sign[x][y+1] = 0  
            dfs(x,y+1,space+1)       
            sign[x][y+1] = 1      
  
  
  
if __name__ == '__main__':  
    n = int(input().strip())  
    Graph = [[j for j in input().strip().split()] for i in range(n)]  
    sign = [[1 for j in range(n)] for i in range(n)]    #标记,用来判断这一点是否走过
    xa = 0  
    ya = 0  
    for i in range(n):           #定位A点坐标
        for j in range(n):  
            if Graph[i][j] == 'A':  
                xa = i  
                ya = j  
                break  
    sign[xa][ya] = 0  
    minspace = inf  
    dfs(xa,ya,0)        #开始搜索
    print(minspace)


 

0.0分

1 人评分

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

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区