Problem Description
Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Key Insights
- The problem involves searching for words in a grid of characters.
- Words can be formed by moving horizontally or vertically in the grid.
- Efficient searching can be achieved using a Trie data structure to store the list of words.
- Backtracking is a suitable algorithmic approach to explore possible paths in the grid.
Space and Time Complexity
Time Complexity: O(m * n * 4^L + W), where m and n are the dimensions of the board, L is the maximum length of the words, and W is the number of words.
Space Complexity: O(W + L), where W is the number of words and L is the maximum length of the words stored in the Trie.
Solution
To solve the problem, we will use a Trie to store all the words we need to search for. The Trie allows us to efficiently check if a prefix of a word exists in our list of words while we traverse the board. We will then use backtracking to explore all possible paths on the board starting from each cell. During the exploration, we will mark cells as visited to avoid using them more than once in a word.
- Build a Trie from the list of words.
- Iterate through each cell in the board and start backtracking.
- For each cell, check if it can lead to a valid prefix in the Trie.
- If a complete word is found, add it to the results.
- Continue exploring until all possibilities have been checked.