# -*- coding: utf8 -*-
from collections import deque
class GraphDfs:
@staticmethod
def DFSTraverse(node,connected,visited):
for i in range(len(visited)):
if not visited[i]:
GraphDfs.DFS(i,node,connected,visited)
@staticmethod
def DFS(i,node,connected,visited):
print(node[i]) #visit node
visited[i]=True
for each in connected[i]:
if not visited[each]:
GraphDfs.DFS(each,node,connected,visited)
@staticmethod
def DFSTraverse_NotRecursive(node,connected,visited):
stack=[0]
while stack:
index=stack[-1]
if not visited[index]:
print(node[index])
visited[index]=True
for each in connected[index]:
if not visited[each]:
stack.append(each)
break
if index==stack[-1]:#没有添加新节点到stack中
stack.pop()
if not stack:#可能不是连通图
for each in range(len(visited)):
if not visited[each]:
stack.append(each)
break
@staticmethod
def BFSTraverse(node,connected,visited):
for i in range(len(visited)):
if not visited[i]:
GraphDfs.BFS(i,node,connected,visited)
@staticmethod
def BFS(i,node,connected,visited):
if not visited[i]:
print(node[i])
visited[i]=True
for each in connected[i]:
if not visited[i]:
print(node[each])
visited[each]=True
for each in connected[i]:
if not visited[i]:
GraphDfs.BFS(each,node,connected,visited)
@staticmethod
def BFSTraverse_NotRecursive(node,connected,visited):
queue=deque([])
for i in range(len(visited)):
if not visited[i]:
queue.append(i)
print(node[i])
visited[i]=True
while queue:
index=queue[0]
for each in connected[index]:
if not visited[each]:
queue.append(each)
print(node[each])
visited[each]=True
queue.popleft()
def main():
#使用 邻接表 表示图
node = ['V1','V2','V3','V4','V5','V6','V7','V8','V9','V10']
connected = { 0:[1,2],1:[0,3,4],2:[0,5,6],3:[1,7],\
4:[1,7],5:[2,6],6:[2,5],7:[3,4],8:[9],9:[8]}
print("dfs recursive")
visited = [False for i in range(len(node))]
GraphDfs.DFSTraverse(node,connected,visited)
print("dfs not recursive")
visited = [False for i in range(len(node))]
GraphDfs.DFSTraverse_NotRecursive(node,connected,visited)
print("bfs recursive")
visited = [False for i in range(len(node))]
GraphDfs.BFSTraverse(node,connected,visited)
print("bfs not recursive")
visited = [False for i in range(len(node))]
GraphDfs.BFSTraverse_NotRecursive(node,connected,visited)
if __name__=='__main__':
main()
结果截图: