LeetCode 78

문제 출처

문제

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.


Constraints:

board and word consists only of lowercase and uppercase English letters.
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3

나의 코드

고민을 많이 했는데.. 결국 해결하지 못했다. 아래 코드로는 input data 가 커지니 maximum callstack error 가 발생했다..

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function (board, word) {
  let result = false;

  for (let i = 0; i < board.length; i++) {
    for (let j = 0; j < board[i].length; j++) {
      if (board[i][j] === word[0]) {
        findLetter(i, j, 0, `${i} ${j}`);
        if (result) return result;
      }
    }
  }

  function findLetter(i, j, wordIdx, ...usedIJ) {
    const usedIJArray = Array.prototype.slice.call(usedIJ);

    // console.log(word[wordIdx]);

    if (!result && wordIdx === word.length - 1) {
      result = true;
      return;
    }

    if (!result && board[i + 1] && board[i + 1][j] === word[wordIdx + 1]) {
      if (!usedIJArray.includes(`${i + 1} ${j}`)) {
        findLetter(i + 1, j, wordIdx + 1, 1, ...usedIJ, `${i + 1} ${j}`);
      }
    }

    if (!result && board[i][j + 1] === word[wordIdx + 1]) {
      if (!usedIJArray.includes(`${i} ${j + 1}`)) {
        findLetter(i, j + 1, wordIdx + 1, 2, ...usedIJ, `${i} ${j + 1}`);
      }
    }

    if (!result && board[i - 1] && board[i - 1][j] === word[wordIdx + 1]) {
      if (!usedIJArray.includes(`${i - 1} ${j}`)) {
        findLetter(i - 1, j, wordIdx + 1, 3, ...usedIJ, `${i - 1} ${j}`);
      }
    }

    if (!result && board[i][j - 1] === word[wordIdx + 1]) {
      if (!usedIJArray.includes(`${i} ${j - 1}`)) {
        findLetter(i, j - 1, wordIdx + 1, 4, ...usedIJ, `${i} ${j - 1}`);
      }
    }
  }

  return result;
};

참고 코드

const exist = (board, word) => {
  if (board.length === 0) return false;

  const h = board.length;
  const w = board[0].length;
  const dirs = [
    [-1, 0],
    [0, 1],
    [1, 0],
    [0, -1],
  ];

  const go = (x, y, k) => {
    if (board[x][y] !== word[k]) return false;
    if (k === word.length - 1) return true;

    board[x][y] = "*"; // mark as visited
    for (const [dx, dy] of dirs) {
      const i = x + dx;
      const j = y + dy;
      if (i >= 0 && i < h && j >= 0 && j < w) {
        if (go(i, j, k + 1)) return true;
      }
    }
    board[x][y] = word[k]; // reset
    return false;
  };

  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (go(i, j, 0)) return true;
    }
  }

  return false;
};

배운점