Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 07e6921

Browse files
committed
Add solution #212
1 parent 2ece86c commit 07e6921

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

0212-word-search-ii.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 212. Word Search II
3+
* https://leetcode.com/problems/word-search-ii/
4+
* Difficulty: Hard
5+
*
6+
* Given an m x n board of characters and a list of strings words, return all words on the board.
7+
*
8+
* Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells
9+
* are horizontally or vertically neighboring. The same letter cell may not be used more than once
10+
* in a word.
11+
*/
12+
13+
/**
14+
* @param {character[][]} board
15+
* @param {string[]} words
16+
* @return {string[]}
17+
*/
18+
var findWords = function(board, words) {
19+
const root = {};
20+
const result = new Set();
21+
const m = board.length;
22+
const n = board[0].length;
23+
24+
words.forEach(w => w.split('').reduce((n, c) => n[c] = n[c] || {}, root).word = w);
25+
26+
for (let i = 0; i < m; i++) {
27+
for (let j = 0; j < n; j++) {
28+
dfs(i, j, root);
29+
}
30+
}
31+
32+
return Array.from(result);
33+
34+
function dfs(i, j, node) {
35+
const char = board[i][j];
36+
const next = node[char];
37+
if (!next) return;
38+
if (next.word) {
39+
result.add(next.word);
40+
}
41+
board[i][j] = '#';
42+
for (const [di, dj] of [[0, 1], [1, 0], [0, -1], [-1, 0]]) {
43+
if (i + di >= 0 && i + di < m && j + dj >= 0 && j + dj < n && board[i + di][j + dj] !== '#') {
44+
dfs(i + di, j + dj, next);
45+
}
46+
}
47+
board[i][j] = char;
48+
}
49+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@
193193
209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium|
194194
210|[Course Schedule II](./0210-course-schedule-ii.js)|Medium|
195195
211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium|
196+
212|[Word Search II](./0212-word-search-ii.js)|Hard|
196197
213|[House Robber II](./0213-house-robber-ii.js)|Medium|
197198
214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard|
198199
215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium|

0 commit comments

Comments
 (0)