-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboggleWordChecker.js
41 lines (38 loc) · 962 Bytes
/
boggleWordChecker.js
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
function checkWord(board, word) {
const rows = board.length;
const cols = board[0].length;
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
function dfs(i, j, k) {
if (k === word.length) {
return true;
}
if (i < 0 || i >= rows || j < 0 || j >= cols || visited[i][j]) {
return false;
}
if (board[i][j] !== word[k]) {
return false;
}
visited[i][j] = true;
const res =
dfs(i - 1, j - 1, k + 1) ||
dfs(i - 1, j, k + 1) ||
dfs(i - 1, j + 1, k + 1) ||
dfs(i, j - 1, k + 1) ||
dfs(i, j + 1, k + 1) ||
dfs(i + 1, j - 1, k + 1) ||
dfs(i + 1, j, k + 1) ||
dfs(i + 1, j + 1, k + 1);
visited[i][j] = false;
return res;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (board[i][j] === word[0]) {
if (dfs(i, j, 0)) {
return true;
}
}
}
}
return false;
}