-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
36 lines (30 loc) · 744 Bytes
/
Copy pathsolution.js
File metadata and controls
36 lines (30 loc) · 744 Bytes
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
class Solution {
isWordExist(mat, word) {
const n = mat.length;
const m = mat[0].length;
const dir = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
const dfs = (i, j, idx) => {
if (idx === word.length) return true;
if (i < 0 || j < 0 || i >= n || j >= m || mat[i][j] !== word[idx])
return false;
const temp = mat[i][j];
mat[i][j] = "#";
for (let [dx, dy] of dir) {
if (dfs(i + dx, j + dy, idx + 1)) return true;
}
mat[i][j] = temp;
return false;
};
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (dfs(i, j, 0)) return true;
}
}
return false;
}
}