deno.land / x / masx200_leetcode_test@10.6.5 / word-search-ii / index.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { PrefixTreeInsert,} from "../design-add-and-search-words-data-structure/PrefixTreeInsert.ts";import { PrefixTree } from "../implement-trie-prefix-tree/PrefixTree.ts";
function findWords(board: string[][], words: string[]): string[] { const ans = new Set(words);
if (board.length === 1 && board[0].length === 1) { return words.filter( (word) => word.length === 1 && word === board[0][0], ); } if (words.length === 0) return []; words.forEach((w) => { if (w.length === 0) { ans.delete(w); } }); const row = board.length; if (!row) { return []; } const col = board[0].length; if (!col) { return []; }
const all_chars = new Set(board.flat()); words.forEach((word) => { if (Array.prototype.some.call(word, (c) => !all_chars.has(c))) { ans.delete(word); } });
words = Array.from(ans);
const result = new Set<string>();
const root = PrefixTree(); for (const word of ans) { PrefixTreeInsert(root, word); } const visited: boolean[][] = Array.from(board).map((a) => Array.from(a).map(() => false) ); for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { if (root.children.has(board[i][j])) { dfs(i, j, visited, board, row, col, "", root, result); } } }
return Array.from(result);}const directions: Array<[number, number]> = [ [0, 1], [1, 0], [0, -1], [-1, 0],];
function dfs( i: number, j: number, visited: boolean[][], board: string[][], row: number, col: number, prefix: string, now: PrefixTree, result: Set<string>,) { const node = now.children.get(board[i][j]); if (!node) return; if (node?.isEnd) { result.add(prefix + board[i][j]); node.isEnd = false; } if (visited[i][j]) { return; } visited[i][j] = true; prefix += board[i][j]; now = node; for (const [f, s] of directions) { const x = i + f; const y = j + s; if (x >= 0 && y >= 0 && x < row && y < col && !visited[x][y]) { dfs(x, y, visited, board, row, col, prefix, now, result); } } visited[i][j] = false; return false;}
export default findWords;
masx200_leetcode_test

Version Info

Tagged at
a year ago