好的,以下是一份示例代码,可以实现你所需要的三个功能:
```python
import queue
# 定义图的邻接矩阵,这里使用二维列表表示
graph = [
[0, 1, 1, 0, 0, 0],
[1, 0, 0, 1, 1, 0],
[1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 1],
[0, 0, 1, 1, 1, 0],
]
# 定义深度优先遍历函数
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for next_node, connected in enumerate(graph[start]):
if connected and next_node not in visited:
dfs(graph, next_node, visited)
# 定义广度优先遍历函数
def bfs(graph, start):
visited = set()
q = queue.Queue()
q.put(start)
visited.add(start)
while not q.empty():
node = q.get()
print(node, end=' ')
for next_node, connected in enumerate(graph[node]):
if connected and next_node not in visited:
q.put(next_node)
visited.add(next_node)
# 定义最短路径函数
def shortest_path(graph, start):
dist = [float('inf')] * len(graph)
dist[start] = 0
q = queue.Queue()
q.put(start)
while not q.empty():
node = q.get()
for next_node, connected in enumerate(graph[node]):
if connected and dist[node] + 1 < dist[next_node]:
dist[next_node] = dist[node] + 1
q.put(next_node)
return dist
# 深度优先遍历
print('深度优先遍历:')
dfs(graph, 0)
print()
# 广度优先遍历
print('广度优先遍历:')
bfs(graph, 0)
print()
# 最短路径
print('最短路径:')
dist = shortest_path(graph, 0)
print(dist)
```
在这个示例代码中,我们使用了以下三个函数:
- `dfs(graph, start, visited=None)`:深度优先遍历函数,其中 `graph` 表示邻接矩阵,`start` 表示遍历的起点,`visited` 表示已经访问过的节点集合,如果 `visited` 为 `None`,则表示还没有访问任何节点。该函数会输出遍历序列。
- `bfs(graph, start)`:广度优先遍历函数,与深度优先遍历函数类似,其中 `graph` 和 `start` 含义相同,该函数也会输出遍历序列。
- `shortest_path(graph, start)`:最短路径函数,其中 `graph` 和 `start` 含义相同,该函数会返回一个列表,表示源点 `start` 到图中每个点的最短路径长度。在本示例代码中,我们使用了队列 `queue.Queue()` 来辅助实现广度优先遍历和最短路径算法。
当然,在实际应用中,以上三个函数的具体实现会因为不同的应用场景而有所不同。