[백준 6593번] BFS(너비 우선 탐색) - 상범빌딩

김민지·2023년 8월 17일
0

냅다 시작 백준

목록 보기
77/118

✨ 문제 ✨

✨ 정답 ✨

const { count } = require("console");
const fs = require("fs");
const { nextTick } = require("process");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./예제.txt";
let input = fs.readFileSync(filePath).toString().trim();


// const fs = require('fs'); 
// let input = fs.readFileSync("/dev/stdin").toString().trim();

input = input.split('\n')

let dFloor = [0, 0, 0, 0, -1, 1]
let dx = [1, -1, 0, 0, 0, 0]
let dy = [0, 0, 1, -1, 0, 0]

const solution = (L, R, C, start, end, floors) => {
  let visited = Array.from({ length: L }, () => Array.from({ length: R }, () => new Array(C).fill(false)))

  let count = 0;
  let [endFloor, endX, endY] = end
  let queue = [[...start, count]]
  let isPossible = false;

  while (queue.length) {
    let [currentFloor, currentX, currentY, count] = queue.shift();
    if (visited[currentFloor][currentX][currentY] === true) {
      continue;
    }
    visited[currentFloor][currentX][currentY] = true;
    count += 1;

    for (let i = 0; i < dFloor.length; i++) {
      let nextFloor = currentFloor + dFloor[i]
      let nextX = currentX + dx[i]
      let nextY = currentY + dy[i]

      if (nextFloor >= 0 && nextFloor < L && nextX >= 0 && nextX < R && nextY >= 0 && nextY < C) {

        if (visited[nextFloor][nextX][nextY] === true) {
          continue;
        } else {
          if (floors[nextFloor][nextX][nextY] === 'E') {
            isPossible = true;
            return `Escaped in ${count} minute(s).`;
          } else if (floors[nextFloor][nextX][nextY] === '.') {
            queue.push([nextFloor, nextX, nextY, count]);
          }
        }
      }
    }
  }

  if (isPossible === false) {
    return 'Trapped!'
  } else {
    return `Escaped in ${count} minute(s).`;
  }
}

let index = 0;
while (true) {
  let [L, R, C] = input.shift().split(' ').map((el) => +el);
  if (L === 0 && R === 0 && C === 0) {
    break;
  }
  let floors = Array.from({ length: L }, () => [])
  for (let i = 0; i < L; i++) {
    for (let j = 0; j < R; j++) {
      floors[i].push(input.shift().trim().split(''))
    }
    input.shift();
  }
  let start = []
  let end = []
  floors.map((el, index) => el.map((el2, index2) => el2.map((el3, index3) => el3 === 'S' ? start.push(index, index2, index3) : el3 === 'E' ? end.push(index, index2, index3) : null)))
  console.log(solution(L, R, C, start, end, floors))
}

🧵 참고한 정답지 🧵

💡💡 기억해야 할 점 💡💡

테스트케이스 넣는거 어렵다. 침착하게 생각해야 한다.

profile
이건 대체 어떻게 만든 거지?

0개의 댓글