We are given a 2D grid of characters and a dictionary of valid words.
We need to find the longest word that can be formed by moving from one cell to an adjacent one (horizontally or vertically) without revisiting the same cell.
The word must be present in the given dictionary.
Approach:
- We can use backtracking (DFS) from each cell to explore all possible paths and check if the formed string is in the dictionary.
- However, the dictionary might be large, and we don't want to explore paths that cannot lead to a valid word. So, we can use a Trie to store the dictionary and prune the search when the current path is not a prefix of any word in the dictionary.
Steps:
a. Build a Trie from the dictionary. The Trie will help us to quickly check if the current string is a prefix of any word. If not, we can backtrack.
b. For each cell in the grid, start a DFS. During DFS, we:
- Mark the current cell as visited (so we don't revisit in the same path).
- Append the current cell's character to the current string.
- Check in the Trie if the current string is a prefix. If not, backtrack (unmark and return).
- If the current string is a word in the dictionary (i.e., the Trie node has an end-of-word marker), then we can update the longest word found (if this word is longer, or same length but lexicographically smaller? The problem says "longest", so if there are multiple of same length, we might need to return one. But the problem doesn't specify which one if multiple. Let's assume we return the first longest we find? Actually, we might want the lexicographically smallest among the longest? The problem says "the longest word", so if there are multiple, we can return any? But to be consistent, let's return the lexicographically smallest among the longest? However, the problem doesn't specify. Let's stick to the first longest we find? But note: we are doing DFS from every cell, and we might find a longer word later. So we should keep track of the longest word(s) and then at the end choose the longest and if multiple, maybe the lexicographically smallest? But the problem says "find the longest word", so we can return any longest. However, let's design to return the longest and if there are multiple, return the lexicographically smallest? But that might require storing all longest words and then comparing. Alternatively, we can update the best word when we find a word that is longer, or same length and lexicographically smaller.
However, note: the problem says "longest", so we are only concerned with the maximum length. If multiple words have the same maximum length, we can return any. But to be deterministic, let's return the lexicographically smallest among the longest? But the problem doesn't specify. Let's assume we return the first longest we find? But that depends on the order of DFS. Instead, we can do:
- Keep a variable
best_word that stores the current best (longest, and if same length then lexicographically smallest?).
But note: we are doing DFS from every cell, and we might find a word of length 5 at the beginning and then later a word of length 6, so we update. But if we find another word of length 6 that is lexicographically smaller, we might want to update? The problem says "the longest word", so if there are multiple of the same maximum length, we can return any. However, let's read the problem again: "find the longest word". It doesn't say "the lexicographically smallest longest word". So we can return any of the longest.
But to be consistent and to avoid having to store all longest words (which might be many), we can do:
- When we find a word, if its length is greater than the current best, update best to this word.
- If same length, we can either keep the current best or update if the new one is lexicographically smaller? Since the problem doesn't specify, let's just keep the first one we find of that length? But then if we find a longer one later, we update. However, if we find a word of the same length as the current best but lexicographically smaller, we might not update. But if we are doing DFS from every cell, the order of finding words of the same length might be arbitrary.
Let's decide: We want the longest word. If there are multiple, we return the one that is found first in our DFS? But DFS order is not well-defined for multiple starting points. Alternatively, we can collect all words of the maximum length and then at the end choose the lexicographically smallest? That would require storing all words of the maximum length until we finish.
However, note that the grid is of fixed size, so the maximum length of a word is at most the number of cells (n*m). So we can do:
- We can run the DFS and whenever we find a word, we compare its length with the current maximum. If longer, update the maximum and set the best word to this one. If same length, we can compare lexicographically and update if the new word is lexicographically smaller? But then we are returning the lexicographically smallest among the longest. But again, the problem doesn't specify.
Let me re-read: "find the longest word". In many such problems, if there are multiple longest words, we return the lexicographically smallest. But it's not stated.
Since the problem is a variation of "Word Search", and in the classic Word Search II (Leetcode) we return all words, but here we only need the longest. So let's assume we need the longest, and if there are multiple, we return the lexicographically smallest.
Steps for the algorithm:
-
Build a Trie from the dictionary. The Trie node will have:
- children: dictionary mapping char to TrieNode
- is_end: boolean to mark the end of a word.
-
We'll do DFS from every cell. We'll have a visited matrix to avoid revisiting the same cell in the current path.
-
In the DFS function (i, j, node, current_string):
- node is the current Trie node we are at (corresponding to the current_string).
- current_string is the string formed so far (we can also build it by appending, but we can also just use the node to check if we are at a word? We need the string to compare for best word and to return? Actually, we need to know the word when we find it. So we can build the string as we go, or we can store the word in the Trie node? But multiple words might share the same prefix. So we can build the string by appending.
However, we can avoid building the string at every step by storing the current string in the DFS call. But that might be expensive in terms of memory? But the maximum depth is at most n*m, and we are already using recursion. Alternatively, we can store the current string as a list and then convert to string when we find a word? But then we have to pass the list around. Alternatively, we can store the current string in the Trie node? That's not possible because the same node can be reached by different paths? Actually, in the Trie, the node represents a prefix, but the same prefix can be formed by different paths? No, the prefix is fixed. But we are building the string by the path in the grid, so the string is determined by the path. So we can build the string by appending the current character.
Let's do:
current_string += grid[i][j]
But note: we are doing DFS, so we need to backtrack the current_string. We can use a list and pop when backtracking.
Alternatively, we can avoid storing the entire string until we find a word? But we need to compare for the best word. So we have to store the string when we find a word.
We can do:
Let's use a list `path` that stores the characters in the current path. Then when we find a word, we convert to string.
But then we are storing a list that we pass around. Alternatively, we can store the current string in the Trie node? No, because the same Trie node can be reached by different paths? Actually, the Trie node is determined by the prefix, so for a given prefix, the node is the same. But the prefix is the same string, so the string is the same. However, we are building the string from the grid, so if we reach the same Trie node by two different paths, they must have formed the same string? Yes, because the Trie node is for that exact string. So we can store the string in the node? But then we are storing the same string multiple times? Actually, we can store the string in the node only at the end? Not necessary.
Example: grid = [['a','a']], and we start at (0,0) and then go to (0,1) -> "aa". Also start at (0,1) and then go to (0,0) -> "aa". So we would find "aa" twice. But when we update the best_word, we compare and it's the same, so no change.
-
We are using a global variable best_word? Or we can return it from the function? Since we are doing DFS from every cell, we can have a variable in the outer function.
-
Edge cases:
- The dictionary might have words of length 1? Yes.
- The grid might be empty? Then return empty string? But the problem says there is a grid, so we assume non-empty? Let's assume grid is at least 1x1.
-
We must be cautious about the time complexity. In the worst case, we are doing DFS from every cell and exploring all paths. But with Trie pruning, we stop when the prefix is not in the dictionary. So it's efficient if the dictionary is small or the words are short.
-
However, note: the Trie is built from the dictionary. We are only exploring paths that are prefixes of words in the dictionary. So if the dictionary has a word of length L, we will explore all paths that form that word? But we are also exploring all prefixes. So the number of nodes in the Trie is at most the total number of characters in the dictionary. And for each node, we might be visited multiple times from different starting cells and different paths? But the same Trie node (prefix) might be reached by multiple paths. So we are not caching the fact that from a given cell and a given Trie node, we have already explored? Actually, the state is (i, j, node) and the visited matrix. But the visited matrix is different for each path. So we cannot cache because the visited set is different.
But note: the same (i, j, node) might be reached by different paths that have the same visited set? Possibly, but the visited set is the set of cells visited so far. So if we are at the same cell and the same Trie node, but the set of visited cells is different, then the future paths are different. So we cannot cache by (i, j, node) alone.
-
Alternatively, we can use memoization with (i, j, node) and the visited set? But the visited set is a matrix of booleans, which is too big to cache.
-
So we rely on the Trie to prune and hope that the dictionary doesn't have too many long words.
-
Let's write the code accordingly.
Steps:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
def build_trie(dictionary):
root = TrieNode()
for word in dictionary:
node = root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_end = True
return root
Then in the main function:
rows = len(grid)
cols = len(grid[0])
visited = [[False]*cols for _ in range(rows)]
best_word = ""
def dfs(i, j, node, current_list):
nonlocal best_word
c = grid[i][j]
if c not in node.children:
return
next_node = node.children[c]
current_list.append(c)
if next_node.is_end:
word = ''.join(current_list)
if len(word) > len(best_word) or (len(word) == len(best_word) and word < best_word):
best_word = word
for di, dj in [(0,1),(1,0),(0,-1),(-1,0)]:
ni, nj = i+di, j+dj
if 0<=ni<rows and 0<=nj<cols and not visited[ni][nj]:
visited[ni][nj] = True
dfs(ni, nj, next_node, current_list)
visited[ni][nj] = False
current_list.pop()
for i in range(rows):
for j in range(cols):
visited[i][j] = True
dfs(i, j, root, [])
visited[i][j] = False
return best_word
20. But note: we are starting from every cell, and for each starting cell, we are doing a DFS that might explore many paths. However, the Trie pruning will help.
-
What if the dictionary has very long words? Then the DFS might go deep. But the grid size is limited, so the maximum depth is rows*cols.
-
We can also optimize by not starting from a cell if the character at that cell is not the first character of any word in the dictionary? Actually, we are checking in the DFS: if the current character is not in the root's children, then we skip. But we are starting the DFS from the cell and then checking. We can precompute a set of first characters of words in the dictionary and skip cells that are not in that set? That would avoid starting DFS from cells that cannot start any word.
But note: a word might start with a character that appears in the dictionary as the first character, but the cell's character might be that. So we can do:
first_chars = set(word[0] for word in dictionary)
Then in the outer loop:
if grid[i][j] not in first_chars:
continue
But note: the dictionary might have words of length 1? Then the first character is the whole word. So we still need to consider.
However, if the cell's character is not in the first_chars, then no word in the dictionary starts with that character? Actually, that's true. So we can skip.
But wait: what if the word is of length 1? Then the first character is the only character. So if the cell's character is that, then it's in first_chars. So we are safe.
So we can add:
first_chars = set()
for word in dictionary:
if word: # non-empty
first_chars.add(word[0])
Then in the outer loop:
if grid[i][j] not in first_chars:
continue
This will reduce the number of starting points.
23. Another optimization: we can also check if the current node (in the DFS) has any children? If not, then we can stop? But we are already checking by the next step: when we try to go to a neighbor, we check if the neighbor's character is in the next_node.children. But in the current node, we have already moved to next_node. So if next_node has no children, then we cannot extend the word. But we are already at the current cell and we have added it. So if next_node has no children, then we cannot go further, but we have already checked if it's an end. So we can break early? Actually, we are going to loop over the neighbors and for each neighbor, we check if the neighbor's character is in next_node.children. If next_node has no children, then for every neighbor, the condition fails. So we are doing unnecessary loops. We can check:
if not next_node.children:
current_list.pop()
return
But note: we have already appended the current character and checked for end. So we can do:
if next_node.is_end:
... update best_word ...
if not next_node.children:
current_list.pop()
return
Then we don't need to loop over neighbors.
24. However, what if the current cell's character leads to a node that has children, but then the neighbors might not have the required characters? Then we still loop and for each neighbor, we check if the neighbor's character is in next_node.children. So the above optimization would only help if the node has no children at all. But if it has children, we still have to check each neighbor.
-
Alternatively, we can precompute for each cell and each Trie node? That's too much.
-
Let's stick to the basic DFS with Trie pruning and the first_chars optimization.
-
Also, note: we are using a list for current_list and appending and popping. This is efficient.
-
We must be cautious about the nonlocal keyword in Python. We are inside a function, and we are modifying best_word. We can also use a class variable or pass by reference? But in Python, we can use nonlocal if we are in a nested function.
-
Let's write the function accordingly.
-
But note: the dictionary might have duplicate words? We are building the Trie, so duplicate words will be stored only once? Actually, we are setting is_end to True, so if the same word is inserted multiple times, it's still one node. So it's okay.
-
What about case sensitivity? The problem says "characters", so we assume the grid and dictionary are in the same case? Let's assume they are all lowercase? But the problem doesn't specify. We'll assume the grid and dictionary are in the same case and we don't change case.
-
Let's code accordingly.
-
However, note: the grid might have uppercase and the dictionary lowercase? The problem doesn't specify. We'll assume the grid and dictionary are in the same case. If not, we can convert both to the same case.
-
But to be safe, we can convert the grid and the dictionary to lowercase? But then the output word should be in the original case? The problem says "formed by moving", so we are using the grid's characters. So if the grid has uppercase, then the word we form will be uppercase. But the dictionary might be lowercase. Then we would never match. So we should convert both to the same case? But the problem doesn't specify.
Since the problem says "a dictionary of valid words", and the grid is given, it's likely they are in the same case. We'll assume that.
- If we want to be case-insensitive, we can convert both to lowercase when building the Trie and when accessing the grid. But then the output word should be in the original case? Actually, the problem says "the longest word", so if the dictionary has "abc" and the grid has "ABC", then we would form "ABC" and it should match? But if the dictionary is in lowercase, then "ABC" is not in the dictionary. So we must convert to the same case.
Let's assume we are told that the grid and dictionary are in the same case. Otherwise, we can do:
Convert the grid to lowercase? But then the output word would be lowercase. But the problem says "formed by moving", so we are using the grid's characters. So if the grid has uppercase, we want to output uppercase? But then the dictionary must have uppercase. So to avoid confusion, we assume the grid and dictionary are in the same case.
36. We'll write the function without case conversion.
-
Let's code accordingly.
-
One more optimization: we can sort the dictionary by length descending and break early if we find a word that is as long as the maximum possible? But we don't know the maximum possible. We can keep track of the current best length and then if we are in the DFS and the current path length plus the maximum possible remaining (which is the number of unvisited cells) is less than the current best, we can prune? But that's complicated because we don't know the maximum length of a word that can be formed from the current node. The Trie node might have a maximum depth? We can precompute the maximum depth of each Trie node? That's the maximum length of a word that has the current prefix. But that might not be achievable in the grid because of the grid's constraints.
Alternatively, we can compute the maximum possible length from the current cell: it's the number of unvisited cells. So if the current path length + number of unvisited cells <= current best length, then we can prune? But that's not correct because we might not be able to use all unvisited cells (they might not form a valid word). So it's not safe.
-
We'll stick to the Trie pruning.
-
Let's write the code.
-
We'll assume the input grid is a list of lists of characters, and dictionary is a list of strings.
-
We'll return the longest word. If there are multiple, we return the lexicographically smallest among the longest? We'll do that by updating when we find a word that is longer, or same length and lexicographically smaller.
-
But note: we are doing DFS, so we might find a word of the same length but lexicographically larger first, and then later a lexicographically smaller one. So we want to update even if same length and lexicographically smaller.
-
However, if we want to return the first longest we find (without worrying about lexicographical order), then we only update when longer. But then if we find two words of the same maximum length, we return the one we found first. But the DFS order is not defined (because we start from every cell and then in each DFS we go in fixed order of directions). So it's arbitrary.
Since the problem says "the longest word", it's ambiguous. Let's assume we return the lexicographically smallest among the longest. So we update when:
- new word is longer, or
- same length and new word < best_word
45. But note: if we find a word of the same length as the current best but lexicographically larger, we don't update.
-
We'll do:
if next_node.is_end:
word = ''.join(current_list)
if len(word) > len(best_word):
best_word = word
elif len(word) == len(best_word) and word < best_word:
best_word = word
-
However, what if best_word is empty? Then we update. So we can initialize best_word as an empty string.
-
But note: the dictionary might have empty string? Then we would form an empty string? But we start from a cell and then we append at least one character. So we cannot form an empty string. So it's safe.
-
Let's code accordingly.
-
We'll also consider the possibility of the grid being very small and the dictionary having very long words. The DFS will be limited by the grid size.
-
Let's write the function.
-
We'll create a class for the solution? Or just a function? We'll write a function.
-
We'll assume the grid is a list of strings? Or list of lists? The problem says "2D grid of characters", so it could be list of strings or list of lists. We'll assume it's a list of lists of single characters.
-
But if it's a list of strings, then grid[i][j] is a character. So it's the same.
-
Let's code.
-
We'll also note that the DFS might be called many times. We are using recursion, and the maximum recursion depth is at most rows*cols. So for a 12x12 grid, that's 144, which is acceptable.
-
Let's write the code.
To solve this problem, we need to find the longest word from a given dictionary that can be formed by moving adjacently (horizontally or vertically) on a 2D grid without revisiting any cell. The solution involves a backtracking DFS combined with a Trie for efficient prefix checks, allowing us to prune paths that cannot lead to valid words early.
Approach
-
Trie Construction: Build a Trie from the dictionary words. Each Trie node stores child nodes for subsequent characters and a flag indicating if it marks the end of a valid word. This allows O(L) prefix checks, where L is the length of the prefix.
-
DFS with Backtracking: For each cell in the grid, initiate a DFS:
- State Tracking: Track visited cells to avoid cycles, the current path's string, and the current Trie node (representing the prefix formed so far).
- Prefix Check: Before exploring further, check if the current path's string exists as a prefix in the Trie. If not, backtrack immediately.
- Word Validation: When the current Trie node marks the end of a word, compare the formed word with the best candidate found so far (prioritizing longer length, then lexicographical order).
- Neighbor Exploration: Recursively explore all four adjacent cells (up, down, left, right) that are within bounds and unvisited.
-
Optimization:
- First Character Filter: Skip starting DFS from cells whose character isn't the first character of any dictionary word.
- Early Termination: If the current Trie node has no children, no further words can be formed along this path, so backtrack immediately.
Solution Code
class TrieNode:
__slots__ = ('children', 'is_end')
def __init__(self):
self.children = {}
self.is_end = False
def build_trie(words):
root = TrieNode()
for word in words:
node = root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
return root
def find_longest_word(grid, dictionary):
if not grid or not grid[0]:
return ""
rows, cols = len(grid), len(grid[0])
trie_root = build_trie(dictionary)
first_chars = {word[0] for word in dictionary if word}
best_word = ""
visited = [[False] * cols for _ in range(rows)]
def dfs(i, j, node, path):
nonlocal best_word
ch = grid[i][j]
if ch not in node.children:
return
next_node = node.children[ch]
path.append(ch)
if next_node.is_end:
word = ''.join(path)
if len(word) > len(best_word) or (len(word) == len(best_word) and word < best_word):
best_word = word
if not next_node.children:
path.pop()
return
for di, dj in [(0,1), (1,0), (0,-1), (-1,0)]:
ni, nj = i + di, j + dj
if 0 <= ni < rows and 0 <= nj < cols and not visited[ni][nj]:
visited[ni][nj] = True
dfs(ni, nj, next_node, path)
visited[ni][nj] = False
path.pop()
for i in range(rows):
for j in range(cols):
if grid[i][j] not in first_chars:
continue
visited[i][j] = True
dfs(i, j, trie_root, [])
visited[i][j] = False
return best_word
Explanation
-
Trie Construction: The build_trie function constructs a Trie where each path from the root to a node with is_end=True represents a dictionary word. This enables efficient prefix checks during DFS.
-
DFS with Backtracking:
- Initialization: For each cell, if its character is a valid starting character (present in
first_chars), start DFS.
- Path Exploration: At each step, append the current cell's character to the path and move to the corresponding Trie node.
- Word Check: If the current Trie node marks the end of a word, update
best_word if the new word is longer or lexicographically smaller among ties.
- Pruning: If the current Trie node has no children, further exploration is futile, so backtrack.
- Recursion: Explore all four adjacent cells, marking them visited before recursion and unmarking after backtracking.
-
Efficiency:
- The Trie ensures we only explore paths that are prefixes of dictionary words.
- The
first_chars set avoids starting DFS from irrelevant cells.
- The worst-case time complexity is O(RC4^L), where R and C are grid dimensions, and L is the maximum word length, but Trie pruning drastically reduces the search space in practice.
This approach efficiently narrows down the search space using the Trie and backtracking, making it suitable for grids up to moderate sizes (e.g., 12x12) with large dictionaries.