Skip to content

BFS โ€‹

  • Queue๋ฅผ ์ด์šฉ
  • ์กฐ๊ฑด์— ๋„๋‹ฌํ–ˆ์„๋•Œ ์š”๊ตฌํ•˜๋Š” ๊ฐ’์„ ์ถœ๋ ฅ๊ฐ€๋Šฅ
  • ์ตœ๋‹จ๊ฑฐ๋ฆฌ ํƒ์ƒ‰์—์„œ ์‚ฌ์šฉ
  • ๋ฐฉ๋ฌธ ์ฒดํฌ
    • ๋ฐฉ๋ฌธํ•ด์•ผํ•  ๊ฒฝ๋กœ๋ฅผ Queue์— ๋„ฃ์–ด๋‘๋Š” ๋™์‹œ์— ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผ ์ค‘๋ณต ๊ฒฝ๋กœ๊ฐ€ Queue์— ๋‹ด๊ธฐ์ง€ ์•Š๋Š”๋‹ค.
  • Queue์˜ ํƒ€์ž…์„ ์ฃผ๋กœ Class๋ฅผ ์„ ์–ธํ•˜์—ฌ Index,Count๋ฅผ ์†์„ฑ์œผ๋กœ ๋‘๊ณ  ๋ชฉํ‘œ ๊ฒฝ๋กœ์— ๋„๋‹ฌํ–ˆ์„๋•Œ Count๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹

https://swexpertacademy.com/main/images/sw_sub/img_visualcodelist_14.png

https://swexpertacademy.com/main/images/sw_sub/img_visualcodelist_02.png

๊ตฌํ˜„ โ€‹

javascript
let arr = [
  [0, 0, 0, 0, 0],
  [0, 1, 1, 1, 0],
  [0, 1, 0, 0, 0],
  [0, 1, 0, 1, 0],
  [0, 0, 0, 1, 0],
]
const directions = [
  [-1, 0],
  [0, 1],
  [1, 0],
  [0, -1],
]

// arr ๋ฐฐ์—ด์˜ [0][0]์—์„œ ์ถœ๋ฐœํ•ด์„œ [4][4]๊นŒ์ง€ ๋„์ฐฉํ•˜๋Š” ๋กœ์ง (0: ๊ธธ, 1: ๋ฒฝ), ๊ธธ์„ ํ†ตํ•ด์„œ๋งŒ ์ด๋™๊ฐ€๋Šฅ
const searchHandler = () => {
  console.log('Breadth First Search')
  const bfsResult = BFS(
    Array.from(Array(5), () => Array(5).fill(false)),
    arr
  )
  console.log('bfsResult', bfsResult)

  console.log('Depth First Search')
  let dfsResult = [Number.MAX_SAFE_INTEGER]
  DFS(
    0,
    0,
    0,
    dfsResult,
    Array.from(Array(5), () => Array(5).fill(false))
  )
  console.log('dfsResult', dfsResult[0])
}

const BFS = (visited, arr) => {
  const start = [0, 0, 0]
  let queue = [start]
  visited[0][0] = true

  while (queue.length) {
    const pos = queue.shift()

    if (pos[0] === arr.length - 1 && pos[1] === arr[0].length - 1) return pos[2]

    for (let dir of directions) {
      const ty = dir[0] + pos[0]
      const tx = dir[1] + pos[1]
      if (0 <= ty && ty < arr.length && 0 <= tx && tx < arr[0].length) {
        if (visited[ty][tx]) continue
        if (arr[ty][tx] === 1) continue
        visited[ty][tx] = true
        queue.push([ty, tx, pos[2] + 1])
      }
    }
  }
}

const DFS = (y, x, depth, answer, visited) => {
  if (arr[y][x] === 1) return
  if (visited[y][x]) return
  if (answer[0] < depth) return
  visited[y][x] = true

  console.log(y, x, depth)

  if (y === arr.length - 1 && x === arr[0].length - 1) {
    answer[0] = Math.min(answer[0], depth)
    return
  }

  for (let dir of directions) {
    const ty = dir[0] + y
    const tx = dir[1] + x
    if (0 <= ty && ty < arr.length && 0 <= tx && tx < arr[0].length) {
      DFS(ty, tx, depth + 1, answer, visited)
    }
  }
}

searchHandler()