一个有向图,节点数,遍数,以及边的链接情况,输出深搜、广搜遍历
时间: 2024-03-15 13:45:05 浏览: 85
图的遍历算法实现(深度和广度搜素)
好的,这里提供两种 Python 代码实现,其中一种是邻接矩阵表示图,一种是邻接表表示图。
邻接矩阵表示图的代码实现:
```python
from collections import deque
# 邻接矩阵表示图
class Graph:
def __init__(self, n):
self.n = n
self.adj = [[0] * n for _ in range(n)]
def add_edge(self, u, v):
self.adj[u][v] = 1
def dfs(self, u, visited):
visited[u] = True
print(u, end=' ')
for v in range(self.n):
if self.adj[u][v] and not visited[v]:
self.dfs(v, visited)
def bfs(self, u):
visited = [False] * self.n
q = deque()
q.append(u)
visited[u] = True
while q:
u = q.popleft()
print(u, end=' ')
for v in range(self.n):
if self.adj[u][v] and not visited[v]:
q.append(v)
visited[v] = True
# 示例
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
visited = [False] * g.n
print("DFS:")
for i in range(g.n):
if not visited[i]:
g.dfs(i, visited)
print("\nBFS:")
g.bfs(2)
```
邻接表表示图的代码实现:
```python
from collections import deque
# 邻接表表示图
class Graph:
def __init__(self, n):
self.n = n
self.adj = [[] for _ in range(n)]
def add_edge(self, u, v):
self.adj[u].append(v)
def dfs(self, u, visited):
visited[u] = True
print(u, end=' ')
for v in self.adj[u]:
if not visited[v]:
self.dfs(v, visited)
def bfs(self, u):
visited = [False] * self.n
q = deque()
q.append(u)
visited[u] = True
while q:
u = q.popleft()
print(u, end=' ')
for v in self.adj[u]:
if not visited[v]:
q.append(v)
visited[v] = True
# 示例
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
visited = [False] * g.n
print("DFS:")
for i in range(g.n):
if not visited[i]:
g.dfs(i, visited)
print("\nBFS:")
g.bfs(2)
```
以上两种实现都可以输出给定有向图的深搜遍历和广搜遍历结果。
阅读全文