Skip to content

Commit faf89d9

Browse files
committed
add: solve #255 Word Search with ts
1 parent 38f0f15 commit faf89d9

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

โ€Žword-search/Yjason-K.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* board ์—์„œ ์ฃผ์–ด์ง„ ๋‹จ์–ด๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€ ํ™•์ธ (boolean)
3+
* @param {string[][]} board - ๋‹จ์–ด๋ฅผ ํƒ์ƒ‰ํ•  2D board
4+
* @param {string} word - ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋‹จ์–ด
5+
* @returns {boolean} - ๋‹จ์–ด๊ฐ€ ๊ฒฉ์ž์—์„œ ์กด์žฌํ•˜๋ฉด true, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด false
6+
*
7+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N * M * 4^L)
8+
* - N: board์˜ ํ–‰ ๊ฐœ์ˆ˜
9+
* - M: board์˜ ์—ด ๊ฐœ์ˆ˜
10+
* - L: word์˜ ๊ธธ์ด
11+
*
12+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(L) (์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ)
13+
*/
14+
function exist(board: string[][], word: string): boolean {
15+
const rows = board.length;
16+
const cols = board[0].length;
17+
18+
// ๋ฐฉํ–ฅ ๋ฐฐ์—ด (์ƒ, ํ•˜, ์ขŒ, ์šฐ)
19+
const directions = [
20+
[0, -1], // ์ƒ
21+
[0, 1], // ํ•˜
22+
[-1, 0], // ์ขŒ
23+
[1, 0], // ์šฐ
24+
];
25+
26+
/**
27+
* DFS ํƒ์ƒ‰(๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰)์„ ํ†ตํ•ด ๋‹จ์–ด๋ฅผ ์ฐพ๋Š” ํ•จ์ˆ˜
28+
* @param {number} x - ํ˜„์žฌ x ์ขŒํ‘œ (์—ด)
29+
* @param {number} y - ํ˜„์žฌ y ์ขŒํ‘œ (ํ–‰)
30+
* @param {number} index - ํ˜„์žฌ ํƒ์ƒ‰ ์ค‘์ธ word์˜ ๋ฌธ์ž ์ธ๋ฑ์Šค
31+
* @returns {boolean} - ํ˜„์žฌ ๊ฒฝ๋กœ๊ฐ€ ์œ ํšจํ•˜๋ฉด true, ์œ ํšจํ•˜์ง€ ์•Š์œผ๋ฉด false
32+
*/
33+
const dfs = (x: number, y: number, index: number): boolean => {
34+
// ๋‹จ์–ด๋ฅผ ๋ชจ๋‘ ์ฐพ์•˜์„ ๊ฒฝ์šฐ
35+
if (index === word.length) return true;
36+
37+
// ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜ ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
38+
if (x < 0 || y < 0 || x >= cols || y >= rows || board[y][x] !== word[index]) {
39+
return false;
40+
}
41+
42+
// ํ˜„์žฌ ์œ„์น˜ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ (์ž„์‹œ ์ˆ˜์ •)
43+
const temp = board[y][x];
44+
board[y][x] = "#";
45+
46+
// ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰
47+
for (const [dx, dy] of directions) {
48+
if (dfs(x + dx, y + dy, index + 1)) {
49+
return true;
50+
}
51+
}
52+
53+
// ๋ฐฑํŠธ๋ž˜ํ‚น: ์…€ ๊ฐ’ ๋ณต๊ตฌ
54+
board[y][x] = temp;
55+
56+
return false;
57+
};
58+
59+
// board์—์„œ word ์ฒซ๊ธ€์ž๊ฐ€ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ ํƒ์ƒ‰ ์‹œ์ž‘
60+
for (let y = 0; y < rows; y++) {
61+
for (let x = 0; x < cols; x++) {
62+
if (board[y][x] === word[0] && dfs(x, y, 0)) {
63+
return true;
64+
}
65+
}
66+
}
67+
68+
return false;
69+
}
70+

0 commit comments

Comments
ย (0)