#太妙了,从Python热门解学到的广搜来解决这道题 #窍门:看到“唯一解”,直接用广搜,这种情况广搜方便的多 #编程技巧:使用递归函数的参数存储自己需要的内容 #行走函数 def moveforward(x,y,route=[(0,0)]):#x,y为当前位置行列数,route为经过的路径 #往四边尝试移动 if x+1<=n-1 and maze[x+1][y]==0 and (x+1,y) not in route:#向右走 moveforward(x+1,y,route+[(x+1,y)])#以x+1,y为当前位置继续走 if x-1>=0 and maze[x-1][y]==0 and (x-1,y) not in route:#向左走 moveforward(x-1,y,route+[(x-1,y)]) if y+1<=m-1 and maze[x][y+1]==0 and (x,y+1) not in route:#向下走 moveforward(x,y+1,route+[(x,y+1)]) if y-1>=0 and maze[x][y-1]==0 and (x,y-1) not in route:#向上走 moveforward(x,y-1,route+[(x,y-1)]) #判断是否到达终点 if x==n-1 and y==m-1: #输出 for i in route: print("({},{})".format(i[0],i[1])) #输入 n,m=map(int,input().split()) maze=[] for i in range(n): maze.append(list(map(int,input().split()))) moveforward(0,0)
注意:
这个解法不是我的原创,是参考了Python热门题解的思路写的。这个解法要比我自己的深搜写法代码少得多,推荐学习这个。
参考题解:
https://blog.nowcoder.net/n/b20decc82fe242668094f0636a59ded5?f=comment