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 でリストを並べ替える方法
sort() メソッドとsorted() 関数を使用して、Python でリストを並べ替える方法を学びます。カスタムキーの並べ替えと逆順の例をご覧ください。
Python 文字列メソッドのチートシート
Python 文字列操作の完全なリファレンス ガイド。文字列プロパティの書式設定、検索、分割、置換、チェックをマスターします。
Python と JavaScript: どちらのプログラミング言語が最適ですか?
Python と JavaScript の包括的な比較。構文の違い、パフォーマンス、使用例 (バックエンドとフロントエンド)、およびコーディング例を調べます。