编写一个函数让用户输入这张图,用邻接表存储。 2、编写函数实现此图的深度优先搜索遍历。 3、编程实现循环队列,编写初始化、创建、入队、出队等算法。 4、利用循环队列对图1实现广度优先搜索遍历。
时间: 2024-01-13 17:05:49 浏览: 69
图的邻接表存储 实现图的深度和广度优先搜索
5星 · 资源好评率100%
1. 下面是一个Python函数示例,用于让用户输入图,并使用邻接表存储:
```python
def create_graph():
graph = {}
nodes = int(input("请输入节点数:"))
for i in range(nodes):
node = input("请输入节点名称:")
edges = input("请输入与该节点相邻的节点名称,用空格隔开:").split()
graph[node] = edges
return graph
```
示例输入:
```
请输入节点数:5
请输入节点名称:A
请输入与该节点相邻的节点名称,用空格隔开:B C
请输入节点名称:B
请输入与该节点相邻的节点名称,用空格隔开:A C D
请输入节点名称:C
请输入与该节点相邻的节点名称,用空格隔开:A B D E
请输入节点名称:D
请输入与该节点相邻的节点名称,用空格隔开:B C E
请输入节点名称:E
请输入与该节点相邻的节点名称,用空格隔开:C D
```
示例输出:
```
{'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D', 'E'], 'D': ['B', 'C', 'E'], 'E': ['C', 'D']}
```
2. 下面是一个Python函数示例,用于实现深度优先搜索遍历:
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for next_node in graph[start]:
if next_node not in visited:
dfs(graph, next_node, visited)
```
示例调用:
```python
graph = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D', 'E'], 'D': ['B', 'C', 'E'], 'E': ['C', 'D']}
dfs(graph, 'A')
```
示例输出:
```
A B C D E
```
3. 下面是一个Python类示例,用于实现循环队列:
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = 0
self.rear = 0
self.size = 0
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.capacity
def enqueue(self, item):
if self.is_full():
raise Exception("队列已满")
self.queue[self.rear] = item
self.rear = (self.rear + 1) % self.capacity
self.size += 1
def dequeue(self):
if self.is_empty():
raise Exception("队列为空")
item = self.queue[self.front]
self.queue[self.front] = None
self.front = (self.front + 1) % self.capacity
self.size -= 1
return item
```
4. 下面是一个Python函数示例,用于实现广度优先搜索遍历:
```python
def bfs(graph, start):
visited = set()
queue = CircularQueue(len(graph))
visited.add(start)
queue.enqueue(start)
while not queue.is_empty():
node = queue.dequeue()
print(node, end=' ')
for next_node in graph[node]:
if next_node not in visited:
visited.add(next_node)
queue.enqueue(next_node)
```
示例调用:
```python
graph = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D', 'E'], 'D': ['B', 'C', 'E'], 'E': ['C', 'D']}
bfs(graph, 'A')
```
示例输出:
```
A B C D E
```
阅读全文