-
Notifications
You must be signed in to change notification settings - Fork 0
/
0079. Word Search.js
57 lines (50 loc) · 1.39 KB
/
0079. Word Search.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Given a 2D board and a word, find if the word exists in the grid.
// The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
//
// Example:
//
// board =
// [
// ['A','B','C','E'],
// ['S','F','C','S'],
// ['A','D','E','E']
// ]
//
// Given word = "ABCCED", return true.
// Given word = "SEE", return true.
// Given word = "ABCB", return false.
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
// https://www.youtube.com/watch?v=oUeGFKZvoo4
//
// Time O(mn * 4^l), l = word.length
// Space O(mn + l)
const exist = (board, word) => {
if (board.length === 0) return false;
const h = board.length;
const w = board[0].length;
const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];
const go = (x, y, k) => {
if (board[x][y] !== word[k]) return false;
if (k === word.length - 1) return true;
board[x][y] = '*'; // mark as visited
for (const [dx, dy] of dirs) {
const i = x + dx;
const j = y + dy;
if (i >= 0 && i < h && j >= 0 && j < w) {
if (go(i, j, k + 1)) return true;
}
}
board[x][y] = word[k]; // reset
return false;
};
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (go(i, j, 0)) return true;
}
}
return false;
};