백준 2206 벽 부수고 이동하기

bkboy·2022년 6월 30일
0

백준 중급

목록 보기
30/31

문제

N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로로 이동하려 한다. 최단경로는 맵에서 가장 적은 개수의 칸을 지나는 경로를 말하는데, 이때 시작하는 칸과 끝나는 칸도 포함해서 센다.

만약에 이동하는 도중에 한 개의 벽을 부수고 이동하는 것이 좀 더 경로가 짧아진다면, 벽을 한 개 까지 부수고 이동하여도 된다.

한 칸에서 이동할 수 있는 칸은 상하좌우로 인접한 칸이다.

맵이 주어졌을 때, 최단 경로를 구해 내는 프로그램을 작성하시오.

입력

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000)이 주어진다. 다음 N개의 줄에 M개의 숫자로 맵이 주어진다. (1, 1)과 (N, M)은 항상 0이라고 가정하자.

출력

첫째 줄에 최단 거리를 출력한다. 불가능할 때는 -1을 출력한다.

입출력 예

풀이

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
class Node {
  constructor(x, y, wall, time) {
    this.x = x;
    this.y = y;
    this.wall = wall;
    this.time = time;
    this.next = null;
  }
}
class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.size = 0;
  }
  push(x, y, wall, time) {
    let node = new Node(x, y, wall, time);
    if (this.size === 0) {
      this.head = node;
    } else {
      this.tail.next = node;
    }
    this.tail = node;
    this.size++;
  }
  shift() {
    let temp = this.head;
    if (this.size === 0) {
      this.head = null;
      this.tail = null;
    } else {
      this.head = this.head.next;
    }
    this.size--;
    return temp;
  }
  length() {
    return this.size;
  }
}
const solution = (input) => {
  const [row, col] = input.shift().split(" ").map(Number);
  const graph = input.map((e) => e.split("").map(Number));
  const visited = Array.from({ length: row }, () =>
    Array.from({ length: col }, () => Array.from({ length: 2 }, () => false))
  );

  const dx = [-1, 0, 1, 0];
  const dy = [0, 1, 0, -1];

  let answer;

  const queue = new Queue();
  queue.push(0, 0, true, 1);

  while (queue.length()) {
    let cur = queue.shift();
    const [x, y, isAble, cnt] = [cur.x, cur.y, cur.wall, cur.time];

    if (x === row - 1 && y === col - 1) {
      answer = cnt;
      break;
    }

    if (visited[x][y][isAble]) continue;

    visited[x][y][isAble] = true;

    for (let i = 0; i < 4; i++) {
      const nx = x + dx[i];
      const ny = y + dy[i];
      const nextCnt = cnt + 1;
      let nextIsAble = isAble;
      if (nx < 0 || ny < 0 || nx >= row || ny >= col) continue;

      if (graph[nx][ny]) {
        if (nextIsAble) nextIsAble = false;
        else continue;
      }
      queue.push(nx, ny, nextIsAble, nextCnt);
    }
  }

  return answer ? answer : -1;
};

console.log(solution(input));

벽이 부서지지 않은 상태의 visited배열과 벽이 부서진 상태의 visited 배열을 따로 관리한다. 추가로 큐 내부에서도 벽을 부술 수 있는지 없는지 관리해줘야한다.

profile
음악하는 개발자

0개의 댓글