forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
51 lines (48 loc) · 1.12 KB
/
Solution.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
function exist(board: string[][], word: string): boolean {
let m = board.length,
n = board[0].length;
let visited = Array.from({ length: m }, v => new Array(n).fill(false));
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (dfs(board, word, i, j, 0, visited)) {
return true;
}
}
}
return false;
}
function dfs(
board: string[][],
word: string,
i: number,
j: number,
depth: number,
visited: boolean[][],
): boolean {
let m = board.length,
n = board[0].length;
if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || visited[i][j]) {
return false;
}
if (board[i][j] != word.charAt(depth)) {
return false;
}
if (depth == word.length - 1) {
return true;
}
visited[i][j] = true;
++depth;
let res = false;
for (let [dx, dy] of [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
]) {
let x = i + dx,
y = j + dy;
res = res || dfs(board, word, x, y, depth, visited);
}
visited[i][j] = false;
return res;
}