Programming & Development / April 19, 2025

Graphs in Python: DFS, BFS, Shortest Path, and Cycle Detection

graphs python dfs bfs shortest path cycle detection graph traversal adjacency list data structures leetcode algorithms

Graphs are powerful data structures used to model relationships between pairs of objects. They consist of nodes (vertices) and connections (edges). Python allows flexible and efficient implementations of both directed and undirected graphs.

๐Ÿ“Œ Graph Representation (Adjacency List)

python

from collections import defaultdict

class Graph:
    def __init__(self, directed=False):
        self.graph = defaultdict(list)
        self.directed = directed

    def add_edge(self, u, v):
        self.graph[u].append(v)
        if not self.directed:
            self.graph[v].append(u)

๐Ÿ” Depth-First Search (DFS)

python

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start, end=" ")
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)

๐Ÿ”„ Breadth-First Search (BFS)

python

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node, end=" ")
            visited.add(node)
            queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited)

๐Ÿ›ฃ๏ธ Shortest Path using BFS (Unweighted Graph)

python

def shortest_path(graph, start, end):
    visited = set()
    queue = deque([(start, [start])])

    while queue:
        current, path = queue.popleft()
        if current == end:
            return path
        for neighbor in graph[current]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append((neighbor, path + [neighbor]))
    return None

๐Ÿ” Cycle Detection (Undirected Graph using DFS)

python

def has_cycle(graph):
    visited = set()

    def dfs(node, parent):
        visited.add(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                if dfs(neighbor, node):
                    return True
            elif neighbor != parent:
                return True
        return False

    for vertex in graph:
        if vertex not in visited:
            if dfs(vertex, None):
                return True
    return False

๐Ÿงช Sample Usage

python

g = Graph(directed=False)
edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
for u, v in edges:
    g.add_edge(u, v)

print("DFS: ", end="")
dfs(g.graph, 0)
print("\nBFS: ", end="")
bfs(g.graph, 0)

print("\nShortest path from 0 to 3:", shortest_path(g.graph, 0, 3))
print("Cycle detected?" , has_cycle(g.graph))

๐Ÿ“ Summary

OperationDescriptionDFSDepth-first traversal using recursionBFSBreadth-first traversal using a queueShortest PathBFS-based shortest path for unweighted graphsCycle DetectionDFS-based method for undirected graph cycle detection

Graphs are foundational in computer science and widely used in real-world applications like networks, maps, and recommendation systems.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex