Skip to content

Commit 2836f79

Browse files
committed
Add word-search solution
1 parent 33aacde commit 2836f79

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

word-search/Jeehay28.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
7+
// board(N * M), where N is the number of row and M is the number of columns
8+
// L, the length of the word
9+
// TC : O(N * M * 4^L)
10+
11+
// recursion depth : the length of the word (L)
12+
// each recursion call requires constant space.
13+
// SC : O(L)
14+
15+
var exist = function (board, word) {
16+
let row = board.length;
17+
let col = board[0].length;
18+
19+
const dfs = (r, c, idx) => {
20+
// search done
21+
if (idx === word.length) {
22+
return true;
23+
}
24+
25+
// row and column are out of range
26+
if (r < 0 || r >= row || c < 0 || c >= col) {
27+
return false;
28+
}
29+
30+
if (board[r][c] !== word[idx]) {
31+
return false;
32+
}
33+
34+
// word[idx] === board[r][c]
35+
// continue searching for word[idx + 1] in adjacent cells on the board
36+
const temp = board[r][c];
37+
board[r][c] = "visited";
38+
39+
const arr = [
40+
[1, 0], // Move down
41+
[-1, 0], // Move up
42+
[0, 1], // Move right
43+
[0, -1], // Move left
44+
];
45+
for (const [up, right] of arr) {
46+
if (dfs(r + up, c + right, idx + 1)) {
47+
return true;
48+
}
49+
}
50+
51+
board[r][c] = temp;
52+
return false;
53+
};
54+
55+
for (let i = 0; i < row; i++) {
56+
for (let j = 0; j < col; j++) {
57+
if (dfs(i, j, 0)) {
58+
return true;
59+
}
60+
}
61+
}
62+
63+
return false;
64+
};
65+
66+
67+

0 commit comments

Comments
 (0)