Skip to content

Commit aeabb3d

Browse files
committed
Word Search solution
1 parent 830a03e commit aeabb3d

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

β€Žword-search/clara-shin.jsβ€Ž

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* μ£Όμ–΄μ§„ 격자(board)μ—μ„œ νŠΉμ • 단어(word)κ°€ μ‘΄μž¬ν•˜λŠ”μ§€ ν™•μΈν•˜λŠ” ν•¨μˆ˜
3+
*
4+
* μ ‘κ·Ό 방식:DFS(깊이 μš°μ„  탐색) + λ°±νŠΈλž˜ν‚Ή
5+
* μ‹œκ°„ λ³΅μž‘λ„: O(m * n * 4^k) (m: ν–‰, n: μ—΄, k: 단어 길이)
6+
* 곡간 λ³΅μž‘λ„: O(m * n) (μ΅œλŒ€ 깊이 m*n)
7+
*
8+
*/
9+
10+
/**
11+
* @param {character[][]} board
12+
* @param {string} word
13+
* @return {boolean}
14+
*/
15+
var exist = function (board, word) {
16+
const m = board.length;
17+
const n = board[0].length;
18+
19+
const directions = [
20+
[-1, 0],
21+
[1, 0],
22+
[0, -1],
23+
[0, 1],
24+
];
25+
26+
function dfs(row, col, index) {
27+
if (index === word.length) {
28+
return true;
29+
}
30+
31+
if (row < 0 || row >= m || col < 0 || col >= n || board[row][col] !== word[index]) {
32+
return false;
33+
}
34+
35+
// ν˜„μž¬ μ…€ λ°©λ¬Έ ν‘œμ‹œ (μž„μ‹œλ‘œ λ³€κ²½)
36+
const temp = board[row][col];
37+
board[row][col] = '#'; // λ°©λ¬Έν•œ 셀을 특수 문자둜 ν‘œμ‹œ
38+
39+
// λ„€ λ°©ν–₯ 탐색
40+
for (const [dx, dy] of directions) {
41+
const newRow = row + dx;
42+
const newCol = col + dy;
43+
44+
if (dfs(newRow, newCol, index + 1)) {
45+
// 단어λ₯Ό μ°Ύμ•˜μœΌλ©΄ μ›λž˜ κ°’ λ‘€λ°± ν›„ true λ°˜ν™˜
46+
board[row][col] = temp;
47+
return true;
48+
}
49+
}
50+
51+
// λ°±νŠΈλž˜ν‚Ή(ν˜„μž¬ μ…€μ˜ μ›λž˜ κ°’ λ‘€λ°±)
52+
board[row][col] = temp;
53+
54+
return false;
55+
}
56+
57+
// 격자의 λͺ¨λ“  μ…€μ—μ„œ μ‹œμž‘μ μœΌλ‘œ μ‹œλ„
58+
for (let i = 0; i < m; i++) {
59+
for (let j = 0; j < n; j++) {
60+
if (board[i][j] === word[0] && dfs(i, j, 0)) {
61+
return true;
62+
}
63+
}
64+
}
65+
66+
// λͺ¨λ“  μ‹œμž‘μ μ—μ„œ μ‹€νŒ¨ν•˜λ©΄
67+
return false;
68+
};

0 commit comments

Comments
Β (0)