דילוג לתוכן הראשי
47

Graph Valid Tree

בינוניgraphsunion find

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

התרגיל הזה משתמש ב:Graphsקראו את המדריך למתחילים

נתונים לכם n nodes שמסומנים מ-0 עד n - 1 ורשימה של קשתות לא מכוונות edges. החזירו true אם הקשתות האלה יוצרות עץ תקין, ו-false אחרת.

הבנת הבעיה

במונחים של גרפים, עץ הוא גרף שהוא גם:

  1. קשיר: אפשר להגיע מכל node לכל node אחר על ידי מעבר על קשתות, וגם
  2. חסר מעגלים: אין בו מעגלים (אין דרך ללכת בלולאה ולחזור למקום שבו התחלתם בלי להשתמש שוב בקשת).

אין כאן root או שמאל/ימין: זו הצורה הכללית של עץ, רק nodes וחיבורים.

דוגמה 1

text
Input:  n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true

      0
    / | \
   1  2  3
   |
   4

הכל מחובר, ואין לולאות.

דוגמה 2

text
Input:  n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false

1 ─ 2 ─ 3 ─ 1 הוא מעגל.

דוגמה 3

text
Input:  n = 4, edges = [[0, 1], [2, 3]]
Output: false

אין מעגלים, אבל {0, 1} ו-{2, 3} לא מחוברים זה לזה.

אילוצים

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • אין קשתות כפולות או לולאות עצמיות.

רמזים

נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.

    הרעיון במשפט אחד

    לעץ עם n nodes יש בדיוק n - 1 קשתות; בודקים את זה קודם, ואז מוסיפים את הקשתות עם Union-Find ונכשלים אם קשת כלשהי מחברת שני nodes שכבר מחוברים (הקשת הזו הייתה סוגרת מעגל).

    התובנה המרכזית: קיצור דרך של ספירה

    נסו לצייר עצים עם 1, 2, 3, 4 nodes. בכל פעם שמוסיפים node לעץ, מחברים אותו בדיוק בקשת חדשה אחת. אז:

    לעץ עם n nodes יש בדיוק 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 לבניית עץ פורש מינימלי.

    פתרון לדוגמה

    js
    /**
     * @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
    }
    ts
    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
    }
    python
    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