解题思路:
深度搜索。
①定位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 人评分
剔除相关数 (C语言代码)浏览:1010 |
1642题解浏览:711 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:342 |
永远的丰碑 (C语言代码)浏览:516 |
C语言程序设计教程(第三版)课后习题8.4 (C语言代码)浏览:553 |
C语言程序设计教程(第三版)课后习题9.10 (C语言代码)浏览:614 |
A+B for Input-Output Practice (II) (C语言代码)浏览:596 |
C语言程序设计教程(第三版)课后习题9.6 (C语言代码)浏览:418 |
C二级辅导-计负均正 (C语言代码)浏览:634 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:449 |