Skip to content

Commit abea895

Browse files
committed
word-search 풀이 추가
1 parent f5193a7 commit abea895

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

word-search/junzero741.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// TC: O(M*N*4^L)
2+
// SC: O(L)
3+
function exist(board: string[][], word: string): boolean {
4+
const rows = board.length;
5+
const cols = board[0].length;
6+
7+
function dfs(r: number, c: number, index: number): boolean {
8+
if (index === word.length) return true;
9+
10+
if (
11+
r < 0 || r >= rows ||
12+
c < 0 || c >= cols ||
13+
board[r][c] !== word[index]
14+
) {
15+
return false;
16+
}
17+
18+
const temp = board[r][c];
19+
board[r][c] = '#';
20+
21+
const found =
22+
dfs(r + 1, c, index + 1) ||
23+
dfs(r - 1, c, index + 1) ||
24+
dfs(r, c + 1, index + 1) ||
25+
dfs(r, c - 1, index + 1);
26+
27+
board[r][c] = temp;
28+
29+
return found;
30+
}
31+
32+
for (let i = 0; i < rows; i++) {
33+
for (let j = 0; j < cols; j++) {
34+
if (board[i][j] === word[0] && dfs(i, j, 0)) {
35+
return true;
36+
}
37+
}
38+
}
39+
40+
return false;
41+
}

0 commit comments

Comments
 (0)