Đồ 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
Python
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]
}BFS (Breadth-First Search)
Python
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 resultDFS (Depth-First Search)
Python
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 resultSo sánh BFS vs DFS
| BFS | DFS | |
|---|---|---|
| Cấu trúc | Queue | Stack/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