[JavaScript 刷题] 搜索 - 单词搜索, leetcode 79

[JavaScript 刷题] 搜索 - 单词搜索, leetcode 79

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:79. Word Search

题目

如下:

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.

解题思路

其实做了 93. 复原 IP 地址 之后,这道题大概能写出来,就是没法 AC,主要的问题还是出在对图的搜索不是很熟悉……

93. 复原 IP 地址 是树的回溯,在遍历完一个组合之后,并不需要考虑下一个结点会访问之前组合的情况——因为树的特性,不同分支的结点时不可及的。但是这道题的处理方式就不太一样:

CESC 为例,其路径如下:

CESC example

但是在 C 进行 DFS 搜索,并且将访问的地点标记之后,其结果如下:

CESC marked

那么问题就出现了,如果不将 C 正下方的点还原,在访问到 CES 之后就结束了,这样自然无法找到正确的结果。

除了这一点要注意之外,其他就和 93. 复原 IP 地址 的做法没什么区别。

使用 JavaScript 解题

必须要注意的就是:

  • 访问过的结点必须要 mark 为已访问
  • 结束访问的结点必须要还原
const isOutOfBound = (grid, row, col) =>
  row < 0 || row >= grid.length || col < 0 || col >= grid[0].length;

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function (board, word) {
    
    
  if (!board || !board[0]) return false;

  const directions = [
    [1, 0],
    [-1, 0],
    [0, 1],
    [0, -1],
  ];

  const backtracking = (row, col, currWord) => {
    
    
    if (isOutOfBound(board, row, col) || board[row][col] !== currWord[0])
      return false;

    if (currWord.length === 1 && board[row][col] === currWord[0]) return true;

    const currChar = board[row][col];
    board[row][col] = null;

    for (const [r, c] of directions) {
    
    
      if (backtracking(row + r, col + c, currWord.slice(1))) {
    
    
        return true;
      }
    }

    board[row][col] = currChar;

    return false;
  };

  for (let i = 0; i < board.length; i++) {
    
    
    for (let j = 0; j < board[i].length; j++) {
    
    
      if (backtracking(i, j, word)) {
    
    
        return true;
      }
    }
  }

  return false;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125741560