题目:
代码:
f=[[1,1,1,1,1,1,1,1,1,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,0,0,1,1,0,0,1], [1,0,1,1,1,0,0,0,0,1], [1,0,0,0,1,0,0,0,0,1], [1,0,1,0,0,0,1,0,0,1], [1,0,1,1,1,0,1,1,0,1], [1,1,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1] ] dirs=[ lambda x,y:(x-1,y), lambda x,y:(x,y+1), lambda x,y:(x+1,y), lambda x,y,:(x,y-1) ]
def stack_keep(x1,y1,x2,y2):
stack=[]
stack.append((x1,y1))
while len(stack)>0:
curnode=stack[-1]
if curnode[0]==x2 and curnode[1]==y2:
for k in stack:
print(k)
return True
for dir in dirs:
nextnode=dir(curnode[0],curnode[1])
if f[nextnode[0]][nextnode[1]]==0:
stack.append(nextnode)
f[nextnode[0]][nextnode[1]]=2
break
else:
f[nextnode[0]][nextnode[1]] = 2
stack.pop()
else:
print('sss')
return False
stack_keep(1,1,8,8)
DFS基础模板:
DFS指的是深度优先搜索 回溯法(会回看前面的节点)
一直往前走,走不下去往回跳
使用stack来进行深度的顺序
把栈顶元素去除,在把临接点放入
#定义一个图的结构
temps={
'A':['B','C'],
'B':['A','C','D'],
'C':['A','B','D','E'],
'D':['B','C','E','F'],
'E':['C','D'],
'F':['D']
}
#只要把bfs的队列改成栈就可以了
def DFS(temps,s):#图 s指的是开始结点
#需要一个队列
stack=[]
stack.append(s)
seen=set()#看是否访问过
seen.add(s)
while (len(stack)>0):
#拿出邻接点
vertex=stack.pop()#这里pop参数没有0了,最后一个元素
nodes=temps[vertex]
for w in nodes:
if w not in seen:#如何判断是否访问过,使用一个数组
stack.append(w)
seen.add(w)
print(vertex)