Leetcode: 212. Word Search II

Problem Statement

Problem Statement

from typing import List


class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        N = len(board)
        M = len(board[0])

        root = {}
        for w in words:
            node = root
            for c in w:
                node.setdefault(c, {})
                node = node[c]
            node["$"] = w

        ans = set()

        def dfs(i, j, node):
            if node.get("$"):
                ans.add(node["$"])
                del node["$"]

            c = board[i][j]
            board[i][j] = "*"
            for di, dj in [[+0, +1], [+0, -1], [+1, +0], [-1, +0]]:
                ni = di + i
                nj = dj + j
                if 0 <= ni < N and 0 <= nj < M and board[ni][nj] in node:
                    dfs(ni, nj, node[board[ni][nj]])
                    if len(node[board[ni][nj]]) == 0:
                        del node[board[ni][nj]]
            board[i][j] = c

        for i in range(N):
            for j in range(M):
                if board[i][j] in root:
                    dfs(i, j, root[board[i][j]])

        return list(ans)


assert Solution().findWords(
    [
        ["o", "a", "a", "n"],
        ["e", "t", "a", "e"],
        ["i", "h", "k", "r"],
        ["i", "f", "l", "v"],
    ],
    ["oath", "pea", "eat", "rain"],
) == ["eat", "oath"]
assert Solution().findWords([["a", "b"], ["c", "d"]], ["abcb"]) == []