Graph and Tree Algorithms
Graph and Tree Algorithms: Traversal algorithms: Depth
First Search (DFS) and Breadth First Search (BFS); Shortest
path algorithms, Transitive closure, Minimum
Spanning Tree, Topological sorting, Network Flow Algorithm.
Here’s a detailed explanation of the Graph and Tree Algorithms mentioned in your query:
1. Traversal Algorithms
a. Depth First Search (DFS)
Strategy: Explore as far as possible along a branch before backtracking.
Uses: Detecting cycles, topological sorting, solving puzzles.
Implementation: Stack (can be explicit or via recursion).
python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited
b. Breadth First Search (BFS)
Strategy: Explore all neighbors level by level.
Uses: Shortest path in unweighted graphs, peer-to-peer networks.
Implementation: Queue.
python
from collections import deque
def bfs(graph, start):
visited = set([start])
queue = deque([start])
while queue:
vertex = queue.popleft()
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return visited
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/3
2. Shortest Path Algorithms
a. Dijkstra’s Algorithm (for graphs with non-negative weights)
Strategy: Greedy
Time Complexity: O((V + E) log V) with a priority queue.
b. Bellman-Ford Algorithm (handles negative weights)
Time Complexity: O(VE)
c. Floyd-Warshall Algorithm (All-pairs shortest path)
Time Complexity: O(V³)
3. Transitive Closure
Definition: Reachability matrix showing whether there is a path from vertex u to v.
Method: Use Floyd-Warshall to determine transitive closure.
4. Minimum Spanning Tree (MST)
a. Kruskal’s Algorithm
Sort edges, pick the smallest one that doesn’t form a cycle (uses Disjoint Set).
Time Complexity: O(E log E)
b. Prim’s Algorithm
Build MST by expanding the cheapest edge from the known part.
Time Complexity: O((V + E) log V) with a heap.
5. Topological Sorting
Applicable to: Directed Acyclic Graphs (DAGs)
Use: Task scheduling, build systems, etc.
Methods:
DFS + Stack (reverse postorder)
Kahn’s Algorithm (BFS with in-degree count)
6. Network Flow Algorithm
Ford-Fulkerson Method (including Edmonds-Karp Implementation)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/3
Goal: Maximize flow from source to sink.
Time Complexity: O(E * max_flow) or O(VE²) for Edmonds-Karp.
Concepts:
Residual graph
Augmenting paths
Would you like a summarized diagram of these algorithms or use cases for each?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/3