Skip to content

Commit c30f3a0

Browse files
committed
Word Search
1 parent b4e20bd commit c30f3a0

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

word-search/sunjae95.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* dfs
5+
*
6+
* time complexity: O(n^2 * 4^word.length)
7+
* space complexity: O(n^2)
8+
*/
9+
10+
var exist = function (board, word) {
11+
let answer = false;
12+
const ROW_LENGTH = board.length;
13+
const COLUMN_LENGTH = board[0].length;
14+
// O(n^2)
15+
const visited = Array.from({ length: ROW_LENGTH }, () =>
16+
Array.from({ length: COLUMN_LENGTH }, () => false)
17+
);
18+
19+
const isRange = (r, c) =>
20+
r >= 0 && r < ROW_LENGTH && c >= 0 && c < COLUMN_LENGTH && !visited[r][c];
21+
22+
const search = (r, c, currentWord) => {
23+
if (answer) return;
24+
if (currentWord.length > word.length) return;
25+
if (!word.includes(currentWord)) return;
26+
if (currentWord === word) {
27+
answer = true;
28+
return;
29+
}
30+
31+
const dr = [-1, 0, 0, 1];
32+
const dc = [0, -1, 1, 0];
33+
34+
for (let i = 0; i < 4; i++) {
35+
const nextR = r + dr[i];
36+
const nextC = c + dc[i];
37+
38+
if (!isRange(nextR, nextC)) continue;
39+
40+
const nextWord = currentWord + board[nextR][nextC];
41+
42+
visited[nextR][nextC] = true;
43+
search(nextR, nextC, nextWord);
44+
visited[nextR][nextC] = false;
45+
}
46+
};
47+
48+
for (let r = 0; r < ROW_LENGTH; r++) {
49+
for (let c = 0; c < COLUMN_LENGTH; c++) {
50+
visited[r][c] = true;
51+
search(r, c, board[r][c]);
52+
visited[r][c] = false;
53+
}
54+
}
55+
56+
return answer;
57+
};

0 commit comments

Comments
 (0)