华为的一道机试题目,不知道为什么自己脑子抽了一下想了很久很久(其实主要还是DFS太不熟了
代码也不是很elegant,将就记录一下。
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
def dfs(graph, stack, destination, hasLoop, visited):
if(len(stack) == 0):
return False
else:
v = stack[-1]
temp = graph[v]
while temp.next is not None:
if v==destination:
visited = [0]*10
visited[v] = 1
if temp.next.data == destination:
hasLoop[destination] = 1
print(stack)
else:
if visited[temp.next.data] == 0 and temp.next.data>destination:
visited[temp.next.data] = 1
stack.append(temp.next.data)
dfs(graph, stack, destination,hasLoop,visited)
temp &#