Graph Intro
Understand graphs as networks: adjacency lists, BFS/DFS traversal, and why graphs appear in maps, social networks, and recommendation systems.
A graph represents connections between things. Examples: - roads between cities - followers on social media - dependencies in projects ## Adjacency list (best common representation) ```python graph = { "A": ["B", "C"], "B": ["D"], "C": ["D"], "D": [] } ``` ## DFS traversal ```python def dfs(graph, start): visited = set() def visit(node): if node in visited: return visited.add(node) print(node) for nxt in graph.get(node, []): visit(nxt) visit(start) dfs(graph, "A") ``` ## BFS traversal ```python from collections import deque def bfs(graph, start): visited = set([start]) q = deque([start]) while q: node = q.popleft() print(node) for nxt in graph.get(node, []): if nxt not in visited: visited.add(nxt) q.append(nxt) bfs(graph, "A") ``` ## Graph diagram ```mermaid flowchart LR A --> B A --> C B --> D C --> D ``` ## Remember - Graph = nodes + edges - adjacency list is common in Python - DFS and BFS are core traversal tools