-
Notifications
You must be signed in to change notification settings - Fork 0
/
79.word-search.ts
63 lines (56 loc) · 1.1 KB
/
79.word-search.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
function exist(board: string[][], word: string): boolean {
const rows = board.length;
const cols = board[0].length;
const paths = new Set<string>();
function backtrace(r: number, c: number, i: number) {
if (i === word.length) {
return true;
}
if (
r < 0 ||
r >= rows ||
c < 0 ||
c >= cols ||
board[r][c] !== word[i] ||
paths.has(`${r}, ${c}`)
) {
return false;
}
paths.add(`${r}, ${c}`);
const result =
backtrace(r + 1, c, i + 1) ||
backtrace(r - 1, c, i + 1) ||
backtrace(r, c + 1, i + 1) ||
backtrace(r, c - 1, i + 1);
paths.delete(`${r}, ${c}`);
return result;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (backtrace(i, j, 0)) {
return true;
}
}
}
return false;
}
console.log(
exist(
[
["A", "B", "C", "E"],
["S", "F", "C", "S"],
["A", "D", "E", "E"],
],
"ABCCED"
)
);
console.log(
exist(
[
["A", "B", "C", "E"],
["S", "F", "C", "S"],
["A", "D", "E", "E"],
],
"SEE"
)
);