Skip to content

Commit

Permalink
4. word search
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Sep 6, 2024
1 parent 3b1229b commit d0efeef
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions word-search/whewchews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* ์กฐ๊ฑด
* ๊ฐ™์€ ๋‹จ์–ด ์œ„์น˜๋Š” ํ•œ๋ฒˆ๋งŒ ์“ฐ์ธ๋‹ค
* ์ด์›ƒํ•ด์„œ ์—ฐ์†๋œ ๋‹จ์–ด๊ฐ€ ์žˆ๋Š”์ง€ ์ฐพ๋Š”๋‹ค
* ๋ฐฑํŠธ๋ž˜ํ‚น
* ๋ชจ๋“  ์›์†Œ๋ฅผ ์™„์ „ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•œ ๋ชฉ์ ์œผ๋กœ ์‚ฌ์šฉ.
* ๋‹จ์ˆœํžˆ ์™„์ „ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์กฐ๊ฑด์— ๋”ฐ๋ผ์„œ ์œ ๋งํ•œ ๋…ธ๋“œ๋กœ ์ด๋™.
*/
function exist(board: string[][], word: string): boolean {
const m = board.length;
const n = board[0].length;
const l = word.length;
const directions = [
[-1, 0], // ์ƒ
[1, 0], // ํ•˜
[0, -1], // ์ขŒ
[0, 1], // ์šฐ
];

const backtrack = (
col: number,
row: number,
idx: number,
visited: Set<string>
): boolean => {
if (idx === l) {
return true;
}
if (
col < 0 ||
col >= m ||
row < 0 ||
row >= n ||
board[col][row] !== word[idx] ||
visited.has(`${col},${row}`)
) {
return false;
}

visited.add(`${col},${row}`);

for (const [dCol, dRow] of directions) {
if (backtrack(col + dCol, row + dRow, idx + 1, visited)) {
return true;
}
}

visited.delete(`${col},${row}`);
return false;
};

for (let col = 0; col < m; col++) {
for (let row = 0; row < n; row++) {
if (backtrack(col, row, 0, new Set<string>())) {
return true;
}
}
}
return false;
}

// TC: O(m*n*4^l) <= m*n: ๋ณด๋“œ์˜ ํฌ๊ธฐ, l: ๋‹จ์–ด์˜ ๊ธธ์ด. ์ตœ๋Œ€ 4๊ฐœ ๋ฐฉํ–ฅ์œผ๋กœ ์ด๋™ ๊ฐ€๋Šฅ
// SC: O(l) <= ๋‹จ์–ด ๊ธธ์ด๋งŒํผ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅ

0 comments on commit d0efeef

Please sign in to comment.