python深度优先搜索算法代码
时间: 2023-11-07 21:05:29 浏览: 118
深度优先搜索算法源代码
4星 · 用户满意度95%
深度优先搜索算法的Python代码如下所示:
```python
class Node:
def __init__(self, value=None, connect=[]):
self.value = value
self.connect = connect
def setValue(self, value):
self.value = value
def getValue(self):
return self.value
def setConnect(self, connect):
self.connect = connect
def getConnect(self):
return self.connect
def addConnect(self, node):
self.connect.append(node)
def dfs(node=None):
if node is None:
return
nodeSet = set()
stack = []
print(node.getValue())
nodeSet.add(node)
stack.append(node)
while len(stack) > 0:
cur = stack.pop()
for next in cur.getConnect():
if next not in nodeSet:
print(next.getValue())
nodeSet.add(next)
stack.append(cur)
stack.append(next)
break
```
阅读全文