Skip to content

[Leetcode] 79. Word Search ​

Problem ​

문제링크

λ³΄λ“œνŒμ˜ μ•ŒνŒŒλ²³μ„ μ΄μ–΄κ°€λ©΄μ„œ μ΄μš©ν•˜μ—¬ word λ₯Ό λ§Œλ“€κΈ°

Solution ​

DFS, Backtracking

λ³΄λ“œνŒμ˜ μ•ŒνŒŒλ²³μ„ ν•œλ²ˆμ”©λ§Œ μ‚¬μš©ν•˜μ—¬ μΈμ ‘ν•œ μ•ŒνŒŒλ²³μ„ λΆ™μ–΄λ‚˜κ°€λ©΄μ„œ wordλ₯Ό λ§Œλ“€μ–΄λ‚΄λŠ” 문제.

  1. DFS ν•¨μˆ˜λ₯Ό 생성
  2. νƒ€κ²Ÿμ„ λ§Œλ‚¬μ„λ•Œ DFS νƒˆμΆœ 쑰건과 탐색 λ²”μœ„λ₯Ό μ΄ˆκ³Όν–ˆμ„λ•Œ 쑰건을 μ΄μš©ν•˜μ—¬ κ°€μ§€μΉ˜κΈ°ν•œλ‹€.
    • 정닡을 μ°Ύμ•˜μ„λ• 성곡 μ—¬λΆ€λ₯Ό νŒŒμ•…ν•˜μ˜€κΈ° λ•Œλ¬Έμ— λͺ¨λ“  ν•¨μˆ˜ 싀행을 μ’…λ£Œν•˜λ„λ‘ν•œλ‹€.
    • ν˜„μž¬ 길이가 word의 λ¬Έμžμ—΄ 길이λ₯Ό μ΄ˆκ³Όν•˜μ˜€μ„λ•Œ 싀행을 μ’…λ£Œν•œλ‹€.
    • λ‹€μŒ μΈλ±μŠ€κ°€ λ³΄λ“œνŒμ˜ λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜μ§€ μ•Šλ„λ‘ν•œλ‹€.
    • 이미 ν•œλ²ˆ μ‚¬μš©ν•œ μ•ŒνŒŒλ²³μ„ μ‚¬μš©ν•˜μ§€ λͺ»ν•˜λ„λ‘ν•œλ‹€.
    • wordλ₯Ό λ§Œλ“œλŠ”λ° ν•„μš”ν•œ μ•ŒνŒŒλ²³μΈμ§€ ν™•μΈν•œλ‹€.
  3. μ‚¬μš©μ—¬λΆ€μ˜ μ²΄ν¬λŠ” DFSκ°€ 싀행이 μ’…λ£Œλ˜λŠ” μ‹œμ μ—μ„œ 이전 depth의 ν•¨μˆ˜μ—κ²Œ λŒλ €μ€˜μ•Όν•œλ‹€.
  4. DFS의 졜초 μ‹€ν–‰ 쑰건에 word의 μ•žκΈ€μžμ™€ λ™μΌν•œμ§€ 쑰건을 μΆ”κ°€ν•˜μ—¬ 속도λ₯Ό κ°œμ„ ν•œλ‹€.

TS Code ​

ts
function exist(board: string[][], word: string): boolean {
  let answer = false
  const dirs = [
    [1, 0],
    [0, 1],
    [-1, 0],
    [0, -1],
  ]
  const visited = Array.from(Array(board.length), (_, i): boolean[] => Array(board[i].length).fill(false))
  const DFS = (y: number, x: number, str: string) => {
    if (answer) return
    if (word.length < str.length) return
    if (word === str) {
      answer = true
      return
    }

    for (const [dy, dx] of dirs) {
      const ty = dy + y
      const tx = dx + x

      if (0 <= ty && ty < board.length && 0 <= tx && tx < board[ty].length) {
        if (visited[ty][tx]) continue
        const c = board[ty][tx]
        if (c !== word[str.length]) continue
        visited[ty][tx] = true
        DFS(ty, tx, str + c)
        visited[ty][tx] = false
      }
    }
  } // DFS

  for (let i = 0; i < board.length; i++) {
    for (let j = 0; j < board[i].length; j++) {
      if (word[0] !== board[i][j]) continue

      visited[i][j] = true
      DFS(i, j, board[i][j])
      visited[i][j] = false
    }
  }

  return answer
}