A Graph is a collection of nodes (vertices) connected by edges. Graphs model relationships everywhere: social networks (friends), maps (roads), the internet (links)! 🌐
💡 Think of it like this: Think of a city map. Each city is a node, and each road between cities is an edge. Some roads are one-way (directed), others go both ways (undirected).
Two main ways to explore a graph:
visited set to avoid infinite loops in cycles!💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Graph problems are ~25% of coding interviews! Master BFS and DFS, and you'll handle: Number of Islands, Course Schedule, Shortest Path, and many more.
from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
print(node, end=' ')
for neighbor in graph[node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
bfs(0)
[0, 1, 2, 3, 4]