Python实战开发及案例分析(24)—— 图搜索算法

        图搜索算法在计算机科学和人工智能领域中广泛应用,主要用于解决路径查找和优化问题。以下是如何使用Python实现常见图搜索算法的方法及其案例分析。

1. 深度优先搜索(Depth-First Search, DFS)

实现步骤

  1. 使用栈来存储路径。
  2. 访问一个节点后,将其标记为已访问,并将其邻居节点添加到栈中。
  3. 重复上述过程,直到栈为空或找到目标节点。

代码示例

def depth_first_search(graph, start, goal):
    stack = [(start, [start])]
    visited = set()

    while stack:
        (vertex, path) = stack.pop()
        if vertex in visited:
            continue
        visited.add(vertex)
        for neighbor in graph[vertex]:
            if neighbor == goal:
                return path + [neighbor]
            else:
                stack.append((neighbor, path + [neighbor]))
    return None

# 案例分析
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

print(depth_first_search(graph, 'A', 'F'))
# 输出: ['A', 'C', 'F']

2. 广度优先搜索(Breadth-First Search, BFS)

实现步骤

  1. 使用队列来存储路径。
  2. 访问一个节点后,将其标记为已访问,并将其邻居节点添加到队列中。
  3. 重复上述过程,直到队列为空或找到目标节点。

代码示例

from collections import deque

def breadth_first_search(graph, start, goal):
    queue = deque([(start, [start])])
    visited = set()

    while queue:
        (vertex, path) = queue.popleft()
        if vertex in visited:
            continue
        visited.add(vertex)
        for neighbor in graph[vertex]:
            if neighbor == goal:
                return path + [neighbor]
            else:
                queue.append((neighbor, path + [neighbor]))
    return None

# 案例分析
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

print(breadth_first_search(graph, 'A', 'F'))
# 输出: ['A', 'C', 'F']

3. A* 搜索算法

实现步骤

  1. 使用优先队列(通常使用堆)来存储路径,优先级为估计的总路径长度。
  2. 访问一个节点后,将其标记为已访问,并将其邻居节点添加到优先队列中。
  3. 重复上述过程,直到优先队列为空或找到目标节点。

代码示例

import heapq

def heuristic(a, b):
    # 使用曼哈顿距离作为启发函数
    return abs(ord(a) - ord(b))

def a_star_search(graph, start, goal):
    queue = [(0, start, [start])]
    visited = set()

    while queue:
        (cost, vertex, path) = heapq.heappop(queue)
        if vertex in visited:
            continue
        visited.add(vertex)
        if vertex == goal:
            return path
        for neighbor in graph[verte
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾贾乾杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值