Skip to Content
🧮 CTDL & Giải thuật🕸️ Đồ thị (Graph)

Đồ thị (Graph)

Graph là gì?

Graph (Đồ thị) gồm tập đỉnh (vertices) kết nối với nhau bởi các cạnh (edges).

💡

Graph mô hình hóa được nhiều vấn đề thực tế: mạng xã hội, bản đồ, mạng máy tính…

Biểu diễn Graph

Adjacency List

from collections import defaultdict graph = defaultdict(list) graph[0].append(1) # 0 -> 1 graph[0].append(2) # 0 -> 2 graph[1].append(2) # 1 -> 2 # Hoặc dùng dict graph = { 0: [1, 2], 1: [2], 2: [0, 3], 3: [3] }
from collections import deque def bfs(graph, start): visited = set([start]) queue = deque([start]) result = [] while queue: node = queue.popleft() result.append(node) for neighbor in graph.get(node, []): if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return result
def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) result = [start] for neighbor in graph.get(start, []): if neighbor not in visited: result.extend(dfs(graph, neighbor, visited)) return result

So sánh BFS vs DFS

BFSDFS
Cấu trúcQueueStack/Recursion
Đường đi ngắn nhất✅ (unweighted)
Bộ nhớO(chiều rộng)O(chiều sâu)

Tiếp theo: Thuật toán tìm kiếm

Last updated on