赞
踩
- import heapq
-
- def dijkstra(graph, start):
- distances = {node: float('inf') for node in graph}
- distances[start] = 0
- heap = [(0, start)]
- while heap:
- (dist, current_node) = heapq.heappop(heap)
- if dist > distances[current_node]:
- continue
- for neighbor, weight in graph[current_node].items():
- distance = dist + weight
- if distance < distances[neighbor]:
- distances[neighbor] = distance
- heapq.heappush(heap, (distance, neighbor))
- return distances
- def bellman_ford(graph, start):
- distances = {node: float('inf') for node in graph}
- distances[start] = 0
- for _ in range(len(graph) - 1):
- for node in graph:
- for neighbor, weight in graph[node].items():
- if distances[node] + weight < distances[neighbor]:
- distances[neighbor] = distances[node] + weight
- return distances
- def floyd_warshall(graph):
- distances = graph
- for k in graph:
- for i in graph:
- for j in graph:
- distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j])
- return distances
- import heapq
- from math import sqrt
-
- def euclidean_distance(a, b):
- return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
-
- def a_star(graph, start, end):
- open_set = set([start])
- closed_set = set()
- g = {node: float('inf') for node in graph}
- g[start] = 0
- parents = {node: None for node in graph}
-
- f = {node: euclidean_distance(graph[node], graph[end]) for node in graph}
-
- while open_set:
- current = min(open_set, key=lambda node: f[node])
- if current == end:
- path = []
- while current:
- path.append(current)
- current = parents[current]
- return list(reversed(path))
-
- open_set.remove(current)
- closed_set.add(current)
-
- for neighbor in graph[current]:
- if neighbor in closed_set:
- continue
-
- tentative_g_score = g[current] + euclidean_distance(graph[current], graph[neighbor])
-
- if neighbor not in open_set:
- open_set.add(neighbor)
- elif tentative_g_score >= g[neighbor]:
- continue
-
- parents[neighbor] = current
- g[neighbor] = tentative_g_score
- f[neighbor] = g[neighbor] + euclidean_distance(graph[neighbor], graph[end])
-
- return None
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。