Graph Traversal For Map

作者:Sys Admin 浏览(202) 评论(0)

Assuming we have the China Map.

And we have 2 axises, so, this is a matrix.

The axis is an array of all the cities of China.

If 2 cities are neighbours, matrix coordinate is 1, or else 0.

So this is a graph.

We need to traverse this map, and each neighbouring places have a distance, by traversing, we can get the total distance between the 2 cities.

Using breadth first traversal or depth first traversal.

DFS实现示例(使用递归和栈)

python# 使用邻接表表示图
graph = {
   'A': ['B', 'C'],
   'B': ['A', 'D', 'E'],
   'C': ['A', 'F'],
   'D': ['B'],
   'E': ['B', 'F'],
   'F': ['C', 'E'],
}

visited = set()  # 用于记录已访问的节点

def dfs(visited, graph, node):
   if node not in visited:
       print(node)  # 访问节点
       visited.add(node)
       for neighbour in graph[node]:
           dfs(visited, graph, neighbour)  # 递归访问邻居节点

# 从节点'A'开始深度优先搜索
dfs(visited, graph, 'A')

BFS实现示例(使用队列)

pythonfrom collections import deque

# 使用邻接表表示图
graph = {
   'A': ['B', 'C'],
   'B': ['A', 'D', 'E'],
   'C': ['A', 'F'],
   'D': ['B'],
   'E': ['B', 'F'],
   'F': ['C', 'E'],
}

visited = set()  # 用于记录已访问的节点
queue = deque()  # 队列用于BFS

def bfs(visited, graph, root):
   visited.add(root)
   queue.append(root)
   
   while queue:
       vertex = queue.popleft()  # 弹出队列中的第一个节点
       print(vertex, end=" ")  # 访问节点
       
       for neighbour in graph[vertex]:
           if neighbour not in visited:
               visited.add(neighbour)
               queue.append(neighbour)  # 将未访问的邻居节点加入队列

# 从节点'A'开始广度优先搜索
bfs(visited, graph, 'A')


没有登录不能评论