Skip to content

79.单词搜索

题解

js
/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function (board, word) {
  const m = board.length;
  const n = board[0].length;
  const used = [];
  const dir = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1],
  ];
  for (let i = 0; i < m; i++) {
    used[i] = [];
  }
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (fn(i, j, "", used)) return true;
    }
  }
  function fn(i, j, str, used) {
    // 匹配到了单词
    if (str === word) {
      return true;
    }
    // 超出范围
    if (i < 0 || j < 0 || i >= m || j >= n || used[i][j]) return false;
    // 关键优化! 如果此路上的字符有不一样的直接return
    if (board[i][j] !== word[str.length]) return false;
    used[i][j] = true;
    for (let k = 0; k < 4; k++) {
      if (fn(i + dir[k][0], j + dir[k][1], str + board[i][j], used)) {
        return true;
      } else {
        continue;
      }
    }
    used[i][j] = false;
    return false;
  }
  return false;
};
/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function (board, word) {
  const m = board.length;
  const n = board[0].length;
  const used = [];
  const dir = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1],
  ];
  for (let i = 0; i < m; i++) {
    used[i] = [];
  }
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (fn(i, j, "", used)) return true;
    }
  }
  function fn(i, j, str, used) {
    // 匹配到了单词
    if (str === word) {
      return true;
    }
    // 超出范围
    if (i < 0 || j < 0 || i >= m || j >= n || used[i][j]) return false;
    // 关键优化! 如果此路上的字符有不一样的直接return
    if (board[i][j] !== word[str.length]) return false;
    used[i][j] = true;
    for (let k = 0; k < 4; k++) {
      if (fn(i + dir[k][0], j + dir[k][1], str + board[i][j], used)) {
        return true;
      } else {
        continue;
      }
    }
    used[i][j] = false;
    return false;
  }
  return false;
};