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

Word Search II

קשהtriebacktracking

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

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

נתונים לכם לוח אותיות board בגודל m x n ורשימת מילים words. החזירו כל מילה מהרשימה שאפשר לשרטט על הלוח, בכל סדר.

הבנת הבעיה

  • כדי לשרטט מילה, מתחילים בתא שמחזיק את האות הראשונה שלה, ואז צועדים לתא שכן לכל אות הבאה.
  • שכנים הם תאים ישירות למעלה, למטה, שמאלה או ימינה (לא באלכסון).
  • אי אפשר להשתמש באותו תא פעמיים באותה מילה.
  • כל מילה שנמצאה מדווחת פעם אחת, גם אם אפשר לשרטט אותה בכמה דרכים.

זו Word Search (מילה אחת על לוח), אבל עם הרבה מילים בבת אחת. אם עוד לא פתרתם את Word Search, תתחילו שם.

דוגמה 1

text
board = [["o","a","a","n"],
         ["e","t","a","e"],
         ["i","h","k","r"],
         ["i","f","l","v"]]
words = ["oath", "pea", "eat", "rain"]

Output: ["eat", "oath"]
  • oath: o (שורה 0, עמודה 0) ← a (ימינה) ← t (למטה) ← h (למטה).
  • eat: e (שורה 1, עמודה 3) ← a (שמאלה) ← t (שמאלה).
  • pea: אין p על הלוח.
  • rain: האותיות r, a, i, n קיימות, אבל לא כמסלול מחובר.

דוגמה 2

text
board = [["a","b"],
         ["c","d"]]
words = ["abcb"]

Output: []

a → b → c כבר נכשל: c לא ליד b. ו-abcb היה צריך את b פעמיים.

אילוצים

  • 1 <= m, n <= 12
  • 1 <= words.length <= 3 * 10^4
  • 1 <= words[i].length <= 10
  • כל האותיות הן אותיות אנגליות קטנות, והמילים ייחודיות.

רמזים

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

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

    שמים את כל המילים ב-trie, ואז מריצים DFS אחד מכל תא שזז בלוח וב-trie באותו זמן, ועוצר ברגע שאף מילה לא מתחילה באותיות ששורטטו עד עכשיו.

    הגישה הנאיבית (ולמה היא איטית)

    מריצים Word Search בנפרד לכל מילה: לכל אחת מעד 30,000 מילים, מנסים DFS מכל תא. הרבה מהעבודה חוזרת: מילים שחולקות התחלה, כמו oat, oath ו-oaths, סורקות שוב ושוב בדיוק את אותם תאים.

    התובנה המרכזית

    מחפשים את כל המילים בבת אחת עם trie:

    1. מכניסים כל מילה ל-trie. ב-node שבו מילה נגמרת, שומרים את המילה עצמה (כדי שנוכל לדווח עליה ישירות).
    2. מכל תא, מתחילים DFS. בכל פעם שצועדים לתא עם אות c, יורדים גם לילד c ב-trie.
    3. אם ל-trie אין ילד בשביל c, אז אף מילה לא מתחילה באותיות ששרטטתם: עוצרים מיד. מכאן מגיעה כל המהירות.
    4. אם ה-node ב-trie מחזיק מילה, מוסיפים אותה לתשובה ומנקים אותה, כדי שתדווח רק פעם אחת.
    5. כשאתם על תא, מסמנים אותו כתפוס (מחליפים את האות ב-#). כשחוזרים אחורה, מחזירים את האות. ביטול השינוי ככה נקרא backtracking.

    צעד אחר צעד

    מילים oath, pea, eat, rain. משרטטים מה-o בפינה השמאלית העליונה:

    תא בלוחאותמסלול ב-trie עד עכשיומה קורה
    (0, 0)ooב-trie יש o (מ-oath): ממשיכים
    (0, 1), ימינהao aקיים ב-trie: ממשיכים
    (1, 1), למטהto a tקיים ב-trie: ממשיכים
    (2, 1), למטהho a t hמילה נגמרת כאן: רושמים oath

    כשמתחילים מ-(1, 0), האות e נמצאת ב-trie (מ-eat), אבל השכנים שלה הם o, t ו-i, ואף אחד מהם לא בא אחרי e ב-trie, אז עוצרים אחרי צעד אחד. מ-(0, 1), ה-a היא לא האות הראשונה של אף מילה: עוצרים עוד לפני שזזים.

    הקוד

    הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.

    כמה זה מהיר?

    עם m × n תאים ו-L = המילה הארוכה ביותר:

    • זמן: במקרה הגרוע בערך O(m · n · 4 · 3^(L-1)): מכל תא, לצעד הראשון יש 4 כיוונים ולכל צעד אחריו לכל היותר 3 (אי אפשר לחזור אחורה). הגיזום של ה-trie הופך את המחיר האמיתי להרבה יותר נמוך.
    • זיכרון: O(סך כל האותיות בכל המילים) ל-trie, ועוד O(L) לרקורסיה.

    טעויות נפוצות

    • לדווח על מילה פעמיים כשאפשר לשרטט אותה בשתי דרכים. מנקים את המילה מה-node ב-trie ברגע שנמצאה.
    • לשכוח להחזיר את התא אחרי החקירה. מסלולים אחרים צריכים את האות הזו.
    • להשתמש בתא שוב באותה מילה. זה מה שהסימון # מונע.

    להעמקה

    גיזום נוסף: אחרי חקירה של node ב-trie, אם לא נשארו לו ילדים ואין בו מילה, מוחקים אותו מההורה שלו. מילים שכבר נמצאו מפסיקות אז למשוך את החיפוש לענפים מתים. הפתרון לדוגמה עושה את זה, וזה משנה בלוחות מלאים באותיות חוזרות, כמו לוח שכולו a.

    פתרון לדוגמה

    js
    /**
     * @param {string[][]} board
     * @param {string[]} words
     * @return {string[]}
     */
    export default function findWords(board, words) {
      // 1. Put every word in a trie. `word` holds the full word when one ends at a node.
      const root = { children: new Map(), word: null }
      for (const word of words) {
        let node = root
        for (const char of word) {
          if (!node.children.has(char)) node.children.set(char, { children: new Map(), word: null })
          node = node.children.get(char)
        }
        node.word = word
      }
    
      const rows = board.length
      const cols = board[0].length
      const found = []
    
      // 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
      function dfs(r, c, parent) {
        const char = board[r][c]
        const node = parent.children.get(char)
        // No word continues with this letter: stop exploring this path.
        if (!node) return
        if (node.word !== null) {
          found.push(node.word)
          node.word = null // report each word only once
        }
        board[r][c] = '#' // mark the cell as used for this path
        for (const [dr, dc] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1],
        ]) {
          const nr = r + dr
          const nc = c + dc
          // Stay on the board, and don't reuse a cell on the current path.
          if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') {
            dfs(nr, nc, node)
          }
        }
        board[r][c] = char // backtrack: give the letter back for other paths
        // Extra pruning: a trie branch with nothing left to find can be removed.
        if (node.children.size === 0 && node.word === null) parent.children.delete(char)
      }
    
      // 3. Try starting from every cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) dfs(r, c, root)
      }
      return found
    }
    ts
    // A trie node. `word` holds the full word when one ends at this node.
    type TrieNode = { children: Map<string, TrieNode>; word: string | null }
    
    export default function findWords(board: string[][], words: string[]): string[] {
      // 1. Put every word in a trie.
      const root: TrieNode = { children: new Map(), word: null }
      for (const word of words) {
        let node = root
        for (const char of word) {
          let child = node.children.get(char)
          if (!child) {
            child = { children: new Map(), word: null }
            node.children.set(char, child)
          }
          node = child
        }
        node.word = word
      }
    
      const rows = board.length
      const cols = board[0].length
      const found: string[] = []
    
      // 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
      function dfs(r: number, c: number, parent: TrieNode): void {
        const char = board[r][c]
        const node = parent.children.get(char)
        // No word continues with this letter: stop exploring this path.
        if (!node) return
        if (node.word !== null) {
          found.push(node.word)
          node.word = null // report each word only once
        }
        board[r][c] = '#' // mark the cell as used for this path
        for (const [dr, dc] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1],
        ]) {
          const nr = r + dr
          const nc = c + dc
          // Stay on the board, and don't reuse a cell on the current path.
          if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') {
            dfs(nr, nc, node)
          }
        }
        board[r][c] = char // backtrack: give the letter back for other paths
        // Extra pruning: a trie branch with nothing left to find can be removed.
        if (node.children.size === 0 && node.word === null) parent.children.delete(char)
      }
    
      // 3. Try starting from every cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) dfs(r, c, root)
      }
      return found
    }
    python
    def find_words(board: list[list[str]], words: list[str]) -> list[str]:
        # 1. Put every word in a trie made of nested dicts. The key "$" holds the full word
        #    when one ends at that node.
        root = {}
        for word in words:
            node = root
            for char in word:
                node = node.setdefault(char, {})
            node["$"] = word
    
        rows, cols = len(board), len(board[0])
        found = []
    
        # 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
        def dfs(r: int, c: int, parent: dict) -> None:
            char = board[r][c]
            node = parent.get(char)
            # No word continues with this letter: stop exploring this path.
            if node is None:
                return
            # pop() removes the word, so each word is reported only once.
            word = node.pop("$", None)
            if word is not None:
                found.append(word)
            board[r][c] = "#"  # mark the cell as used for this path
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                # Stay on the board, and don't reuse a cell on the current path.
                if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
                    dfs(nr, nc, node)
            board[r][c] = char  # backtrack: give the letter back for other paths
            # Extra pruning: a trie branch with nothing left to find can be removed.
            if not node:
                del parent[char]
    
        # 3. Try starting from every cell.
        for r in range(rows):
            for c in range(cols):
                dfs(r, c, root)
        return found