Graph Valid Tree
הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.
נתונים לכם n nodes שמסומנים מ-0 עד n - 1 ורשימה של קשתות לא מכוונות edges. החזירו true אם הקשתות האלה יוצרות עץ תקין, ו-false אחרת.
הבנת הבעיה
במונחים של גרפים, עץ הוא גרף שהוא גם:
- קשיר: אפשר להגיע מכל node לכל node אחר על ידי מעבר על קשתות, וגם
- חסר מעגלים: אין בו מעגלים (אין דרך ללכת בלולאה ולחזור למקום שבו התחלתם בלי להשתמש שוב בקשת).
אין כאן root או שמאל/ימין: זו הצורה הכללית של עץ, רק nodes וחיבורים.
דוגמה 1
Input: n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true
0
/ | \
1 2 3
|
4הכל מחובר, ואין לולאות.
דוגמה 2
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false1 ─ 2 ─ 3 ─ 1 הוא מעגל.
דוגמה 3
Input: n = 4, edges = [[0, 1], [2, 3]]
Output: falseאין מעגלים, אבל {0, 1} ו-{2, 3} לא מחוברים זה לזה.
אילוצים
1 <= n <= 20000 <= edges.length <= 5000- אין קשתות כפולות או לולאות עצמיות.
רמזים
נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.
הרעיון במשפט אחד
לעץ עם n nodes יש בדיוק n - 1 קשתות; בודקים את זה קודם, ואז מוסיפים את הקשתות עם Union-Find ונכשלים אם קשת כלשהי מחברת שני nodes שכבר מחוברים (הקשת הזו הייתה סוגרת מעגל).
התובנה המרכזית: קיצור דרך של ספירה
נסו לצייר עצים עם 1, 2, 3, 4 nodes. בכל פעם שמוסיפים node לעץ, מחברים אותו בדיוק בקשת חדשה אחת. אז:
לעץ עם
nnodes יש בדיוקn - 1קשתות.
- פחות מ-
n - 1קשתות: אין מספיק כדי לחבר הכל. לא עץ. - יותר מ-
n - 1: יש לפחות קשת אחת מיותרת, שחייבת לסגור מעגל. לא עץ. - בדיוק
n - 1: אז "קשיר" ו"אין מעגל" הולכים יחד: אם אחד נכון, גם השני. אז צריך לבדוק רק אחד מהם.
בדיקת מעגל עם Union-Find
Union-Find עוקב אחרי אילו nodes כבר מחוברים, בקבוצות (ראו Number of Connected Components). מוסיפים את הקשתות אחת אחת:
- אם שני הקצוות של הקשת בקבוצות שונות, ממזגים את הקבוצות.
- אם הם כבר באותה קבוצה, כבר היה מסלול ביניהם. הוספת הקשת הזו יוצרת מסלול שני: זה מעגל. מחזירים
false.
אם כל קשת ממזגת שתי קבוצות שונות, אין מעגל, ועם n - 1 קשתות, הגרף הוא עץ.
צעד אחר צעד
n = 4, edges = [[0, 1], [1, 2], [2, 0]]: בדיוק n - 1 = 3 קשתות, אז בדיקת הספירה עוברת.
| קשת | קבוצות לפני | אותה קבוצה? | פעולה |
|---|---|---|---|
[0, 1] | {0} {1} {2} {3} | לא | ממזגים ← {0,1} {2} {3} |
[1, 2] | {0,1} {2} {3} | לא | ממזגים ← {0,1,2} {3} |
[2, 0] | {0,1,2} {3} | כן | מעגל! ← false |
שימו לב ש-node 3 גם מנותק: המעגל "בזבז" קשת שהייתה צריכה לחבר אותו. לכן מספיק לבדוק רק תכונה אחת.
הקוד
הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.
כמה זה מהיר?
עם V nodes ו-E קשתות:
- זמן: בערך O(V + E). כל
findכמעט קבוע בזכות path compression. - זיכרון: O(V) למערך
parent.
טעויות נפוצות
- לבדוק רק מעגלים. בדוגמה 3 אין מעגל, אבל היא לא קשירה. בדיקת ספירת הקשתות תופסת את זה.
- לבדוק רק קשירות עם יותר מ-
n - 1קשתות: הכל יכול להיות מחובר ועדיין להכיל מעגל. - לשכוח את
n = 1בלי קשתות. node בודד הוא עץ תקין:0קשתות= n - 1.
להעמקה
- גם DFS עובד: אחרי בדיקת ספירת הקשתות, מריצים חיפוש מ-node
0וסופרים לכמה nodes הגעתם. זה עץ בדיוק כשמגיעים לכלn. - אותו רעיון של "קשת בתוך קבוצה אחת סוגרת מעגל" מוצא את החיבור המיותר (redundant connection) בגרף, והוא הלב של האלגוריתם של Kruskal לבניית עץ פורש מינימלי.
פתרון לדוגמה
/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/
export default function validTree(n, edges) {
// A tree with n nodes has exactly n - 1 edges. With exactly that many,
// "no cycle" also guarantees "connected", so we only need to look for a cycle.
if (edges.length !== n - 1) return false
// Union-Find: every node starts as its own group, pointing to itself.
const parent = Array.from({ length: n }, (_, i) => i)
// Follow parent pointers up to the group's representative.
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]] // path compression: skip a level for next time
x = parent[x]
}
return x
}
for (const [a, b] of edges) {
const rootA = find(a)
const rootB = find(b)
// Already connected some other way: this edge would close a cycle.
if (rootA === rootB) return false
parent[rootA] = rootB // merge the two groups
}
return true
}export default function validTree(n: number, edges: number[][]): boolean {
// A tree with n nodes has exactly n - 1 edges. With exactly that many,
// "no cycle" also guarantees "connected", so we only need to look for a cycle.
if (edges.length !== n - 1) return false
// Union-Find: every node starts as its own group, pointing to itself.
const parent = Array.from({ length: n }, (_, i) => i)
// Follow parent pointers up to the group's representative.
function find(x: number): number {
while (parent[x] !== x) {
parent[x] = parent[parent[x]] // path compression: skip a level for next time
x = parent[x]
}
return x
}
for (const [a, b] of edges) {
const rootA = find(a)
const rootB = find(b)
// Already connected some other way: this edge would close a cycle.
if (rootA === rootB) return false
parent[rootA] = rootB // merge the two groups
}
return true
}def valid_tree(n: int, edges: list[list[int]]) -> bool:
# A tree with n nodes has exactly n - 1 edges. With exactly that many,
# "no cycle" also guarantees "connected", so we only need to look for a cycle.
if len(edges) != n - 1:
return False
# Union-Find: every node starts as its own group, pointing to itself.
parent = list(range(n))
# Follow parent pointers up to the group's representative.
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression: skip a level for next time
x = parent[x]
return x
for a, b in edges:
root_a, root_b = find(a), find(b)
# Already connected some other way: this edge would close a cycle.
if root_a == root_b:
return False
parent[root_a] = root_b # merge the two groups
return True