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

Lines changed: 50 additions & 0 deletions
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)