Skip to content

Commit 5fddc45

Browse files
authored
[ PS ] : Word Search II
1 parent 2c0b025 commit 5fddc45

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

word-search-ii/uraflower.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// 모든 word에 대해
2+
// board를 순회하면서
3+
// word의 첫 글자가 board의 현 위치 문자와 같다면 dfs
4+
// 이렇게 풀 경우 O(W * m * n * 4^L)만큼 시간이 걸림 (W: words.length, L: word.length)
5+
6+
// 그래서 모든 word를 트라이로 저장하고
7+
// board를 한 번만 순회하는 방법을 사용
8+
9+
const buildTrie = (words) => {
10+
const root = {};
11+
12+
for (const word of words) {
13+
let node = root;
14+
for (const char of word) {
15+
if (!node[char]) node[char] = {};
16+
node = node[char];
17+
}
18+
node.word = word;
19+
}
20+
21+
return root;
22+
}
23+
24+
/**
25+
* @param {character[][]} board
26+
* @param {string[]} words
27+
* @return {string[]}
28+
*/
29+
const findWords = function (board, words) {
30+
const m = board.length;
31+
const n = board[0].length;
32+
const trie = buildTrie(words);
33+
const result = [];
34+
35+
const dr = [0, 0, 1, -1];
36+
const dc = [1, -1, 0, 0];
37+
const visited = Array.from({ length: m }).map(() => Array.from({ length: n }).fill(false));
38+
39+
const dfs = (r, c, node, path) => {
40+
const char = board[r][c];
41+
const nextNode = node[char];
42+
if (!nextNode) return;
43+
44+
if (nextNode.word) {
45+
result.push(nextNode.word);
46+
nextNode.word = null;
47+
}
48+
49+
visited[r][c] = true;
50+
51+
for (let i = 0; i < 4; i++) {
52+
const nr = r + dr[i];
53+
const nc = c + dc[i];
54+
55+
if (0 <= nr && nr < m && 0 <= nc && nc < n && !visited[nr][nc]) {
56+
dfs(nr, nc, nextNode, path + board[nr][nc]);
57+
}
58+
}
59+
60+
visited[r][c] = false;
61+
}
62+
63+
for (let i = 0; i < m; i++) {
64+
for (let j = 0; j < n; j++) {
65+
dfs(i, j, trie, '');
66+
}
67+
}
68+
69+
return result;
70+
};
71+
72+
// 시간복잡도: O(m * n * 4^L) (L: word.length)
73+
// 공간복잡도: O(W * L + m * n)
74+
// - trie: O(W * L) (W: words.length)
75+
// - vistied: O(m * n)
76+
// - 재귀스택: O(L)
77+
// - result: O(K * L) (K: 찾은 단어 수)

0 commit comments

Comments
 (0)