Skip to content

Commit 43853fc

Browse files
committed
feat: 79. Word Search
1 parent e97aff4 commit 43853fc

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

word-search/gwbaik9717.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// h: height of the board, w: width of the board, n: length of the word
2+
// Time complexity: O(h * w * 4**n)
3+
// Space complexity: O(h * w + n)
4+
5+
/**
6+
* @param {character[][]} board
7+
* @param {string} word
8+
* @return {boolean}
9+
*/
10+
var exist = function (board, word) {
11+
const n = word.length;
12+
const h = board.length;
13+
const w = board[0].length;
14+
15+
const dy = [1, 0, -1, 0];
16+
const dx = [0, 1, 0, -1];
17+
18+
const checked = Array.from({ length: h }, () =>
19+
Array.from({ length: w }, () => 0)
20+
);
21+
22+
let answer = false;
23+
24+
const dfs = (current, index) => {
25+
if (index === n - 1) {
26+
answer = true;
27+
return;
28+
}
29+
30+
const [cy, cx] = current;
31+
checked[cy][cx] = 1;
32+
33+
for (let i = 0; i < dy.length; i++) {
34+
const ny = cy + dy[i];
35+
const nx = cx + dx[i];
36+
const ni = index + 1;
37+
38+
if (
39+
ny >= 0 &&
40+
ny < h &&
41+
nx >= 0 &&
42+
nx < w &&
43+
checked[ny][nx] === 0 &&
44+
word[ni] === board[ny][nx]
45+
) {
46+
dfs([ny, nx], ni);
47+
}
48+
}
49+
50+
checked[cy][cx] = 0;
51+
};
52+
53+
for (let i = 0; i < h; i++) {
54+
for (let j = 0; j < w; j++) {
55+
if (board[i][j] === word[0] && !answer) {
56+
dfs([i, j], 0);
57+
}
58+
}
59+
}
60+
61+
return answer;
62+
};

0 commit comments

Comments
 (0)