|
| 1 | +/* |
| 2 | +https://leetcode.com/problems/word-search |
| 3 | +
|
| 4 | +Given an m x n grid of characters board and a string word, return true if word exists in the grid. |
| 5 | +
|
| 6 | +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. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" |
| 10 | +Output: true |
| 11 | +
|
| 12 | +Example 2: |
| 13 | +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" |
| 14 | +Output: true |
| 15 | +Example 3: |
| 16 | +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" |
| 17 | +Output: false |
| 18 | +
|
| 19 | +Constraints: |
| 20 | +m == board.length |
| 21 | +n = board[i].length |
| 22 | +1 <= m, n <= 6 |
| 23 | +1 <= word.length <= 15 |
| 24 | +board and word consists of only lowercase and uppercase English letters. |
| 25 | +
|
| 26 | +Follow up: Could you use search pruning to make your solution faster with a larger board? |
| 27 | +*/ |
| 28 | + |
| 29 | +const wordSearch = (board, word) => { |
| 30 | + function dfs(y, x, i, cache = {}) { |
| 31 | + if (cache[`${y}${x}`]) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + if (y < 0 || y > board.length - 1 || x < 0 || x > board[0].length - 1) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + if (board[y][x] !== word[i]) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + if (board[y][x] === word[word.length - 1] && i === word.length - 1) { |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + cache[`${y}${x}`] = true; |
| 45 | + |
| 46 | + const results = [ |
| 47 | + dfs(y - 1, x, i + 1, { ...cache }), |
| 48 | + dfs(y + 1, x, i + 1, { ...cache }), |
| 49 | + dfs(y, x - 1, i + 1, { ...cache }), |
| 50 | + dfs(y, x + 1, i + 1, { ...cache }), |
| 51 | + ]; |
| 52 | + |
| 53 | + return results.some((result) => result); |
| 54 | + } |
| 55 | + |
| 56 | + for (let y = 0; y < board.length; y++) { |
| 57 | + for (let x = 0; x < board[y].length; x++) { |
| 58 | + if (board[y][x] === word[0]) { |
| 59 | + const result = dfs(y, x, 0); |
| 60 | + if (result) { |
| 61 | + return true; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return false; |
| 68 | +}; |
| 69 | + |
| 70 | +module.exports = { wordSearch }; |
0 commit comments