題目描述: 有 n 個人,給定一些不喜歡對 (a, b) 表示 a 和 b 互相不喜歡。能否將所有人分成兩組,使得每對不喜歡的人在不同組?
解題思路:
時間複雜度:O(n + E) — n 為人數,E 為不喜歡對的數量。每個節點和邊只處理一次
空間複雜度:O(n + E) — 圖的鄰接表和顏色陣列
1. Build undirected graph from dislikes pairs
2. Initialize color array with -1 (uncolored)
3. For each uncolored node i:
a. BFS from i, color it 0
b. For each neighbor v of current node u:
- If uncolored: color v = 1 - color[u], add to queue
- If same color as u: return false (odd cycle found)
4. Return true (all components are bipartite)Union-Find 方法:對每個節點 u,將 u 的所有鄰居合併到同一組(「敵人的敵人是朋友」)。如果發現 u 和某個鄰居在同一組,返回 false。時間複雜度 O(E * α(n)),接近線性。
DFS 染色:與 BFS 類似,用遞迴 DFS 實現。代碼更簡潔但可能受遞迴深度限制。對於稀疏圖效果相同。