Skip to content

Commit b63c83f

Browse files
committed
Add solution #79
1 parent ac6fbbf commit b63c83f

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
75|[Sort Colors](./0075-sort-colors.js)|Medium|
8484
77|[Combinations](./0077-combinations.js)|Medium|
8585
78|[Subsets](./0078-subsets.js)|Medium|
86+
79|[Word Search](./0079-word-search.js)|Medium|
8687
80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium|
8788
81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium|
8889
82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium|

solutions/0079-word-search.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 79. Word Search
3+
* https://leetcode.com/problems/word-search/
4+
* Difficulty: Medium
5+
*
6+
* Given an m x n grid of characters board and a string word, return true if word exists
7+
* in the grid.
8+
*
9+
* The word can be constructed from letters of sequentially adjacent cells, where adjacent
10+
* cells are horizontally or vertically neighboring. The same letter cell may not be used
11+
* more than once.
12+
*/
13+
14+
/**
15+
* @param {character[][]} board
16+
* @param {string} word
17+
* @return {boolean}
18+
*/
19+
var exist = function(board, word) {
20+
function backtrack(x, y, k) {
21+
if (board[x][y] !== word[k]) {
22+
return false;
23+
} else if (k === word.length - 1) {
24+
return true;
25+
}
26+
27+
board[x][y] = '-';
28+
29+
for (const direction of [[-1, 0], [0, 1], [1, 0], [0, -1]]) {
30+
const [i, j] = [x + direction[0], y + direction[1]];
31+
if (i >= 0 && i < board.length && j >= 0 && j < board[0].length) {
32+
if (backtrack(i, j, k + 1)) {
33+
return true;
34+
}
35+
}
36+
}
37+
38+
board[x][y] = word[k];
39+
40+
return false;
41+
}
42+
43+
for (let i = 0; i < board.length; i++) {
44+
for (let j = 0; j < board[0].length; j++) {
45+
if (backtrack(i, j, 0)) {
46+
return true;
47+
}
48+
}
49+
}
50+
51+
return false;
52+
};

0 commit comments

Comments
 (0)