Skip to content

Commit 41be1fb

Browse files
committed
word-search
1 parent 46e55b3 commit 41be1fb

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

β€Žword-search/JANGSEYEONG.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
// DFS μ‚¬μš© 이유: ν•œ 경둜λ₯Ό λκΉŒμ§€ 탐색해야 ν•˜κ³ , κ²½λ‘œλ³„λ‘œ 독립적인 λ°©λ¬Έ μƒνƒœκ°€ ν•„μš”ν•˜κΈ° λ•Œλ¬Έ
7+
// BFS λΆˆκ°€ 이유: μ—¬λŸ¬ 경둜λ₯Ό λ™μ‹œμ— νƒμƒ‰ν•˜λ©΄μ„œ λ°©λ¬Έ μƒνƒœκ°€ μ„žμ—¬ μ˜¬λ°”λ₯Έ 경둜λ₯Ό 놓칠 수 있음
8+
var exist = function (board, word) {
9+
for (let y = 0; y < board.length; y++) {
10+
for (let x = 0; x < board[0].length; x++) {
11+
// μ‹œμž‘μ΄ λ˜λŠ” 단어λ₯Ό 마주치면 dfs 돌렀보기
12+
if (board[y][x] === word[0] && dfs(board, y, x, word, 0)) {
13+
return true;
14+
}
15+
}
16+
}
17+
return false;
18+
};
19+
20+
function dfs(board, y, x, word, index) {
21+
// 성곡 쑰건: λͺ¨λ“  문자λ₯Ό μ°Ύμ•˜μ„ λ•Œ
22+
if (index === word.length) return true;
23+
24+
// μ‹€νŒ¨ 쑰건: λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜κ±°λ‚˜ ν˜„μž¬ κΈ€μžκ°€ μΌμΉ˜ν•˜μ§€ μ•Šμ„ λ•Œ
25+
if (
26+
y < 0 ||
27+
y >= board.length ||
28+
x < 0 ||
29+
x >= board[0].length ||
30+
board[y][x] !== word[index]
31+
) {
32+
return false;
33+
}
34+
35+
// ν˜„μž¬ μ…€ μ‚¬μš© ν‘œμ‹œ
36+
const temp = board[y][x];
37+
board[y][x] = true; // μž„μ‹œ λ°©λ¬Έ ν‘œμ‹œ
38+
39+
// μƒν•˜μ’Œμš° 탐색, ν•˜λ‚˜λΌλ„ μ°Ύκ²Œλœλ‹€λ©΄ true
40+
const found =
41+
dfs(board, y + 1, x, word, index + 1) ||
42+
dfs(board, y - 1, x, word, index + 1) ||
43+
dfs(board, y, x + 1, word, index + 1) ||
44+
dfs(board, y, x - 1, word, index + 1);
45+
46+
// μ›λž˜ κ°’μœΌλ‘œ 볡원 (λ°±νŠΈλž˜ν‚Ή)
47+
board[y][x] = temp;
48+
49+
return found;
50+
}

0 commit comments

Comments
Β (0)