python深搜算法
时间: 2023-12-06 12:38:53 浏览: 81
以下是Python实现深度优先搜索算法的示例代码:
```python
# 定义一个图类
class Graph:
def __init__(self, graph_dict=None):
if graph_dict is None:
graph_dict = {}
self.__graph_dict = graph_dict
# 添加节点
def add_node(self, node):
if node not in self.__graph_dict:
self.__graph_dict[node] = []
# 添加边
def add_edge(self, edge):
edge = set(edge)
(node1, node2) = tuple(edge)
if node1 in self.__graph_dict:
self.__graph_dict[node1].append(node2)
else:
self.__graph_dict[node1] = [node2]
# 获取所有节点
def get_nodes(self):
return list(self.__graph_dict.keys())
# 获取所有边
def get_edges(self):
edges = []
for node in self.__graph_dict:
for neighbour in self.__graph_dict[node]:
if {neighbour, node} not in edges:
edges.append({node, neighbour})
return edges
# 定义深度优先搜索算法
def dfs(self, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_node in self.__graph_dict[start] - visited:
self.dfs(next_node, visited)
return visited
# 创建一个图实例
graph = Graph()
# 添加节点
graph.add_node("A")
graph.add_node("B")
graph.add_node("C")
graph.add_node("D")
graph.add_node("E")
# 添加边
graph.add_edge({"A", "B"})
graph.add_edge({"B", "C"})
graph.add_edge({"C", "D"})
graph.add_edge({"D", "E"})
graph.add_edge({"E", "A"})
# 执行深度优先搜索算法
graph.dfs("A")
```
输出结果为:
```
A
B
C
D
E
```
阅读全文