Skip to content

Commit db8d8eb

Browse files
committed
word-search solution
1 parent ecfc1a1 commit db8d8eb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

word-search/prgmr99.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
var exist = function (board, word) {
7+
const m = board.length;
8+
const n = board[0].length;
9+
10+
const dfs = (row, col, index) => {
11+
if (index === word.length) return true;
12+
13+
if (
14+
row < 0 ||
15+
row >= m ||
16+
col < 0 ||
17+
col >= n ||
18+
board[row][col] !== word[index]
19+
) {
20+
return false;
21+
}
22+
23+
const temp = board[row][col];
24+
board[row][col] = "#";
25+
26+
const found =
27+
dfs(row + 1, col, index + 1) ||
28+
dfs(row - 1, col, index + 1) ||
29+
dfs(row, col + 1, index + 1) ||
30+
dfs(row, col - 1, index + 1);
31+
32+
board[row][col] = temp;
33+
34+
return found;
35+
};
36+
37+
for (let r = 0; r < m; r++) {
38+
for (let c = 0; c < n; c++) {
39+
if (board[r][c] === word[0] && dfs(r, c, 1)) {
40+
return true;
41+
}
42+
}
43+
}
44+
45+
return false;
46+
};

0 commit comments

Comments
 (0)