λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 79 - Word Search (Medium)

by HandHand 2021. 3. 3.

문제

LeetCode - 79번

풀이 κ³Όμ •

이차원 λ°°μ—΄μ—μ„œ μΈμ ‘ν•œ λ¬Έμžλ“€μ„ μ΄μš©ν•΄μ„œ νŠΉμ • 단어λ₯Ό λ§Œλ“€ 수 μžˆλŠ”μ§€ νŒλ‹¨ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

λ°±νŠΈλž˜ν‚Ή 을 ν™œμš©ν•΄μ„œ λ¬Έμžκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμœΌλ©΄ λ‹€μŒ μœ„μΉ˜λ₯Ό 찾도둝 탐색을 ν•˜λ©΄ λ©λ‹ˆλ‹€.
λ˜ν•œ μ›ν•˜λŠ” 단어λ₯Ό 찾으면 λ‹€λ₯Έ λ¬Έμžλ“€μ€ νƒμƒ‰ν•˜μ§€ μ•Šκ³  λ°”λ‘œ true λ₯Ό λ°˜ν™˜ν•˜λ„λ‘ ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
var exist = function (board, word) {
  const dx = [0, 0, 1, -1];
  const dy = [1, -1, 0, 0];

  function dfs(x, y, depth, visit) {
    if (board[x][y] !== word[depth]) return false;
    else if (depth === word.length - 1) return true;

    for (let i = 0; i < 4; i++) {
      const nx = x + dx[i],
        ny = y + dy[i];

      if (0 <= nx && nx < board.length && 0 <= ny && ny < board[0].length) {
        if (!visit[nx][ny]) {
          visit[nx][ny] = 1;
          if (dfs(nx, ny, depth + 1, visit)) return true;
          visit[nx][ny] = 0;
        }
      }
    }

    return false;
  }

  for (let x = 0; x < board.length; x++) {
    for (let y = 0; y < board[0].length; y++) {
      if (board[x][y] === word[0]) {
        const visit = new Array(board.length)
          .fill(0)
          .map((_) => new Array(board[0].length).fill(0));

        visit[x][y] = 1;
        if (dfs(x, y, 0, visit)) return true;
        visit[x][y] = 0;
      }
    }
  }

  return false;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€