Explore tens of thousands of sets crafted by our community.
Graph Traversing Techniques
5
Flashcards
0/5
Depth-First Search (DFS)
DFS(vertex): if vertex is visited: return mark vertex as visited for each neighbor in vertex.adjacent: DFS(neighbor)
Dijkstra's Algorithm
Dijkstra(graph, start): for each vertex v in graph: distance[v] = infinity previous[v] = undefined distance[start] = 0 create vertex set Q for each vertex v in graph: Q.add_with_priority(v, distance[v]) while Q is not empty: u = Q.extract_min() for each neighbor v of u: alt = distance[u] + length(u, v) if alt < distance[v]: distance[v] = alt previous[v] = u Q.decrease_priority(v, alt)
Bellman-Ford Algorithm
BellmanFord(graph, start): distance[start] = 0 for each vertex v in graph: distance[v] = infinity predecessor[v] = null for i from 1 to size(vertices)-1: for each edge (u, v) in edges: if distance[u] + weight(u, v) < distance[v]: distance[v] = distance[u] + weight(u, v) predecessor[v] = u for each edge (u, v) in edges: if distance[u] + weight(u, v) < distance[v]: return 'Graph contains a negative-weight cycle'
A* Search Algorithm
AStar(start, goal): openSet = set containing start cameFrom = an empty map gScore[start] = 0 fScore[start] = gScore[start] + heuristic_cost_estimate(start, goal) while openSet is not empty: current = node in openSet with the lowest fScore value if current = goal: return reconstruct_path(cameFrom, current) openSet.remove(current) for each neighbor of current: tentative_gScore = gScore[current] + dist_between(current, neighbor) if tentative_gScore < gScore[neighbor]: cameFrom[neighbor] = current gScore[neighbor] = tentative_gScore fScore[neighbor] = gScore[neighbor] + heuristic_cost_estimate(neighbor, goal) if neighbor not in openSet: openSet.add(neighbor)
Breadth-First Search (BFS)
BFS(start): create queue Q enqueue start onto Q mark start as visited while Q is not empty: vertex = Q.dequeue() for each neighbor in vertex.adjacent: if neighbor is not visited: mark neighbor as visited enqueue neighbor onto Q
© Hypatia.Tech. 2024 All rights reserved.