-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path0079-word-search.js
52 lines (45 loc) · 1.19 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
/**
* 79. Word Search
* https://leetcode.com/problems/word-search/
* Difficulty: Medium
*
* Given an m x n grid of characters board and a string word, return true if word exists
* in the grid.
*
* The word can be constructed from letters of sequentially adjacent cells, where adjacent
* cells are horizontally or vertically neighboring. The same letter cell may not be used
* more than once.
*/
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
function backtrack(x, y, k) {
if (board[x][y] !== word[k]) {
return false;
} else if (k === word.length - 1) {
return true;
}
board[x][y] = '-';
for (const direction of [[-1, 0], [0, 1], [1, 0], [0, -1]]) {
const [i, j] = [x + direction[0], y + direction[1]];
if (i >= 0 && i < board.length && j >= 0 && j < board[0].length) {
if (backtrack(i, j, k + 1)) {
return true;
}
}
}
board[x][y] = word[k];
return false;
}
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
if (backtrack(i, j, 0)) {
return true;
}
}
}
return false;
};