-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordSearch.js
More file actions
45 lines (40 loc) · 835 Bytes
/
wordSearch.js
File metadata and controls
45 lines (40 loc) · 835 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
37
38
39
40
41
42
43
44
45
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
const wordSearch = (board, word) => {
const set = new Set()
const ROWS = board.length
const COLS = board[0].length
const dfs = (r, c, i) => {
if (word.length === i) {
return true
}
if (
r < 0 ||
c < 0 ||
r >= ROWS ||
c >= COLS ||
word[i] !== board[r][c] ||
set.has(`${r},${c}`)
) {
return false
}
set.add(`${r},${c}`)
const result =
dfs(r + 1, c, i + 1) ||
dfs(r, c + 1, i + 1) ||
dfs(r - 1, c, i + 1) ||
dfs(r, c - 1, i + 1)
set.delete(`${r},${c}`)
return result
}
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
const match = dfs(i, j, 0)
if (match) return true
}
}
return false
}