基于邻接表的深搜和广搜
图:(忽略边权,这里只看边)
import sys
from queue import Queue
sys.setrecursionlimit(1000000)
# 深搜
def dfs(start, graph, vis):
print(start, end=' ')
vis[start] = True
for sub in graph[start]:
if not vis[sub]:
dfs(sub, graph, vis)
# 广搜
def bfs(start, graph):
n = len(graph)
queue = []
queue.append(start)
vis = [False for _ in range(n)]
vis[start] = True
while queue:
tem = queue.pop(0)
print(tem, end=' ')
for sub in graph[tem]:
if not vis[sub]:
queue.append(sub)
vis[sub] = True
def bfs_queue(start, graph):
n = len(graph)
queue = Queue()
queue.put(start)
vis = [False for _ in range(n)]
vis[start] = True
whil