-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
31 lines (31 loc) · 946 Bytes
/
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
function exist(board: string[][], word: string): boolean {
const [m, n] = [board.length, board[0].length];
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number, k: number): boolean => {
if (k === word.length - 1) {
return board[i][j] === word[k];
}
if (board[i][j] !== word[k]) {
return false;
}
const c = board[i][j];
board[i][j] = '0';
for (let u = 0; u < 4; ++u) {
const [x, y] = [i + dirs[u], j + dirs[u + 1]];
const ok = x >= 0 && x < m && y >= 0 && y < n;
if (ok && board[x][y] !== '0' && dfs(x, y, k + 1)) {
return true;
}
}
board[i][j] = c;
return false;
};
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (dfs(i, j, 0)) {
return true;
}
}
}
return false;
}