Word Search II
Detailed guide and Python implementation for the 'Word Search II' problem.
1. Узнать
The 'Word Search II' problem is a key challenge in the Trie section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Word Search II.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Word Search II carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Постановка задачи
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.
Write a function findWords(board: List[List[str]], words: List[str]) -> List[str].
- •m == len(board)
- •n == len(board[i])
- •1 <= m, n <= 12
- •board[i][j] is a lowercase English letter
- •1 <= len(words) <= 3 * 10^4
- •1 <= len(words[i]) <= 10
- •words consist of lowercase English letters
- •All the strings in words are unique
Примеры
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
["oath","eat"]
The words "oath" and "eat" can be found on the board. "pea" and "rain" cannot.
board = [["a","b"],["c","d"]], words = ["abcb"]
[]
The word "abcb" requires using the 'b' cell twice, which is invalid.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Готовы решить?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Интервью: идеи и вариации
Разбивка анализа сложности
Почему время: Directly evaluates all possibilities.
Почему космос: Uses standard local memory.
Почему время: Optimized paths reduce total operations.
Почему космос: May trade memory for speed.
Оптимизированный код Python для решения
Оптимизированный код Python для решения
class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
def addWord(self, word):
curr = self
for c in word:
if c not in curr.children: curr.children[c] = TrieNode()
curr = curr.children[c]
curr.isWord = True
def find_words_opt(board, words):
root = TrieNode()
for w in words: root.addWord(w)
ROWS, COLS = len(board), len(board[0])
res, visit = set(), set()
def dfs(r, c, node, word):
if r < 0 or r == ROWS or c < 0 or c == COLS or (r, c) in visit or board[r][c] not in node.children:
return
visit.add((r, c))
node = node.children[board[r][c]]
word += board[r][c]
if node.isWord: res.add(word)
for dr, dc in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
dfs(r + dr, c + dc, node, word)
visit.remove((r, c))
for r in range(ROWS):
for c in range(COLS):
dfs(r, c, root, "")
return list(res)Код грубой силы (спойлер защищен)
Код грубой силы (спойлер защищен)
def find_words_brute(board, words):
def exist(word):
ROWS, COLS = len(board), len(board[0])
def dfs(r, c, i, visited):
if i == len(word): return True
if r < 0 or c < 0 or r >= ROWS or c >= COLS or (r, c) in visited or board[r][c] != word[i]:
return False
visited.add((r, c))
res = any(dfs(r+dr, c+dc, i+1, visited) for dr, dc in [[1,0],[-1,0],[0,1],[0,-1]])
visited.remove((r, c))
return res
return any(dfs(r, c, 0, set()) for r in range(ROWS) for c in range(COLS))
return [w for w in words if exist(w)]Algorithm Pattern Checklist
When dealing with Trie data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Trie problem properties apply.
Связанные вопросы
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Рекомендуемые ресурсы Python
Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.
Циклы Python
Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.
Как отсортировать список в Python
Узнайте, как сортировать список в Python с помощью метода sort() и функции sorted(). Ознакомьтесь с примерами пользовательской сортировки ключей и обратного порядка.
Шпаргалка по строковым методам Python
Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.
Python против JavaScript: какой язык программирования лучше?
Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.