|
| 1 | +from collections import deque |
| 2 | + |
| 3 | +def bfs(graph, start): |
| 4 | + visited = set() |
| 5 | + queue = deque([start]) |
| 6 | + result = [] |
| 7 | + |
| 8 | + while queue: |
| 9 | + node = queue.popleft() |
| 10 | + if node not in visited: |
| 11 | + visited.add(node) |
| 12 | + result.append(node) |
| 13 | + queue.extend(graph.get(node, []) - visited) |
| 14 | + |
| 15 | + return result |
| 16 | + |
| 17 | +def dfs(graph, start): |
| 18 | + visited = set() |
| 19 | + stack = [start] |
| 20 | + result = [] |
| 21 | + |
| 22 | + while stack: |
| 23 | + node = stack.pop() |
| 24 | + if node not in visited: |
| 25 | + visited.add(node) |
| 26 | + result.append(node) |
| 27 | + stack.extend(graph.get(node, []) - visited) |
| 28 | + |
| 29 | + return result |
| 30 | + |
| 31 | +import heapq |
| 32 | + |
| 33 | +def dijkstra(graph, start): |
| 34 | + distances = {vertex: float('infinity') for vertex in graph} |
| 35 | + distances[start] = 0 |
| 36 | + priority_queue = [(0, start)] |
| 37 | + |
| 38 | + while priority_queue: |
| 39 | + current_distance, current_vertex = heapq.heappop(priority_queue) |
| 40 | + |
| 41 | + if current_distance > distances[current_vertex]: |
| 42 | + continue |
| 43 | + |
| 44 | + for neighbor, weight in graph[current_vertex].items(): |
| 45 | + distance = current_distance + weight |
| 46 | + |
| 47 | + if distance < distances[neighbor]: |
| 48 | + distances[neighbor] = distance |
| 49 | + heapq.heappush(priority_queue, (distance, neighbor)) |
| 50 | + |
| 51 | + return distances |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +def a_star(graph, start, goal): |
| 56 | + open_set = [(0, start)] |
| 57 | + came_from = {} |
| 58 | + g_score = {vertex: float('infinity') for vertex in graph} |
| 59 | + g_score[start] = 0 |
| 60 | + f_score = {vertex: float('infinity') for vertex in graph} |
| 61 | + f_score[start] = heuristic(start, goal) |
| 62 | + |
| 63 | + while open_set: |
| 64 | + _, current = heapq.heappop(open_set) |
| 65 | + |
| 66 | + if current == goal: |
| 67 | + return reconstruct_path(came_from, current) |
| 68 | + |
| 69 | + for neighbor, cost in graph[current].items(): |
| 70 | + tentative_g_score = g_score[current] + cost |
| 71 | + |
| 72 | + if tentative_g_score < g_score[neighbor]: |
| 73 | + came_from[neighbor] = current |
| 74 | + g_score[neighbor] = tentative_g_score |
| 75 | + f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal) |
| 76 | + heapq.heappush(open_set, (f_score[neighbor], neighbor)) |
| 77 | + |
| 78 | + return None |
| 79 | + |
| 80 | +def heuristic(node, goal): |
| 81 | + # Define your heuristic function here (e.g., Manhattan distance, Euclidean distance, etc.) |
| 82 | + pass |
| 83 | + |
| 84 | +def reconstruct_path(came_from, current): |
| 85 | + path = [current] |
| 86 | + while current in came_from: |
| 87 | + current = came_from[current] |
| 88 | + path.append(current) |
| 89 | + return path[::-1] |
| 90 | + |
0 commit comments