class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
}
};
212. 单词搜索 II
给定一个 m x n
二维字符网格 board
和一个单词(字符串)列表 words
, 返回所有二维网格上的单词 。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:
输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] 输出:["eat","oath"]
示例 2:
输入:board = [["a","b"],["c","d"]], words = ["abcb"] 输出:[]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
是一个小写英文字母1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
由小写英文字母组成words
中的所有字符串互不相同原站题解
cpp 解法, 执行用时: 1712 ms, 内存消耗: 15.4 MB, 提交时间: 2023-09-24 18:29:48
struct TrieNode { string word; unordered_map<char,TrieNode *> children; TrieNode() { this->word = ""; } }; void insertTrie(TrieNode * root,const string & word) { TrieNode * node = root; for (auto c : word){ if (!node->children.count(c)) { node->children[c] = new TrieNode(); } node = node->children[c]; } node->word = word; } class Solution { public: int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; bool dfs(vector<vector<char>>& board, int x, int y, TrieNode * root, set<string> & res) { char ch = board[x][y]; if (!root->children.count(ch)) { return false; } root = root->children[ch]; if (root->word.size() > 0) { res.insert(root->word); } board[x][y] = '#'; for (int i = 0; i < 4; ++i) { int nx = x + dirs[i][0]; int ny = y + dirs[i][1]; if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size()) { if (board[nx][ny] != '#') { dfs(board, nx, ny, root,res); } } } board[x][y] = ch; return true; } vector<string> findWords(vector<vector<char>> & board, vector<string> & words) { TrieNode * root = new TrieNode(); set<string> res; vector<string> ans; for (auto & word: words){ insertTrie(root,word); } for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { dfs(board, i, j, root, res); } } for (auto & word: res) { ans.emplace_back(word); } return ans; } };
golang 解法, 执行用时: 260 ms, 内存消耗: 5.7 MB, 提交时间: 2023-09-24 18:29:34
type Trie struct { children [26]*Trie word string } func (t *Trie) Insert(word string) { node := t for _, ch := range word { ch -= 'a' if node.children[ch] == nil { node.children[ch] = &Trie{} } node = node.children[ch] } node.word = word } var dirs = []struct{ x, y int }{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} func findWords(board [][]byte, words []string) []string { t := &Trie{} for _, word := range words { t.Insert(word) } m, n := len(board), len(board[0]) seen := map[string]bool{} var dfs func(node *Trie, x, y int) dfs = func(node *Trie, x, y int) { ch := board[x][y] node = node.children[ch-'a'] if node == nil { return } if node.word != "" { seen[node.word] = true } board[x][y] = '#' for _, d := range dirs { nx, ny := x+d.x, y+d.y if 0 <= nx && nx < m && 0 <= ny && ny < n && board[nx][ny] != '#' { dfs(node, nx, ny) } } board[x][y] = ch } for i, row := range board { for j := range row { dfs(t, i, j) } } ans := make([]string, 0, len(seen)) for s := range seen { ans = append(ans, s) } return ans }
java 解法, 执行用时: 545 ms, 内存消耗: 42.7 MB, 提交时间: 2023-09-24 18:29:21
class Solution { int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public List<String> findWords(char[][] board, String[] words) { Trie trie = new Trie(); for (String word : words) { trie.insert(word); } Set<String> ans = new HashSet<String>(); for (int i = 0; i < board.length; ++i) { for (int j = 0; j < board[0].length; ++j) { dfs(board, trie, i, j, ans); } } return new ArrayList<String>(ans); } public void dfs(char[][] board, Trie now, int i1, int j1, Set<String> ans) { if (!now.children.containsKey(board[i1][j1])) { return; } char ch = board[i1][j1]; now = now.children.get(ch); if (!"".equals(now.word)) { ans.add(now.word); } board[i1][j1] = '#'; for (int[] dir : dirs) { int i2 = i1 + dir[0], j2 = j1 + dir[1]; if (i2 >= 0 && i2 < board.length && j2 >= 0 && j2 < board[0].length) { dfs(board, now, i2, j2, ans); } } board[i1][j1] = ch; } } class Trie { String word; Map<Character, Trie> children; boolean isWord; public Trie() { this.word = ""; this.children = new HashMap<Character, Trie>(); } public void insert(String word) { Trie cur = this; for (int i = 0; i < word.length(); ++i) { char c = word.charAt(i); if (!cur.children.containsKey(c)) { cur.children.put(c, new Trie()); } cur = cur.children.get(c); } cur.word = word; } }
python3 解法, 执行用时: 8916 ms, 内存消耗: 19 MB, 提交时间: 2023-09-24 18:29:08
from collections import defaultdict class Trie: def __init__(self): self.children = defaultdict(Trie) self.word = "" def insert(self, word): cur = self for c in word: cur = cur.children[c] cur.is_word = True cur.word = word class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: trie = Trie() for word in words: trie.insert(word) def dfs(now, i1, j1): if board[i1][j1] not in now.children: return ch = board[i1][j1] now = now.children[ch] if now.word != "": ans.add(now.word) board[i1][j1] = "#" for i2, j2 in [(i1 + 1, j1), (i1 - 1, j1), (i1, j1 + 1), (i1, j1 - 1)]: if 0 <= i2 < m and 0 <= j2 < n: dfs(now, i2, j2) board[i1][j1] = ch ans = set() m, n = len(board), len(board[0]) for i in range(m): for j in range(n): dfs(trie, i, j) return list(ans)