티스토리 뷰

https://www.acmicpc.net/problem/14442

 

14442번: 벽 부수고 이동하기 2

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

www.acmicpc.net

class Node {
  constructor(item) {
    this.item = item;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  push(item) {
    const node = new Node(item);
    if (this.head == null) {
      this.head = node;
    } else {
      this.tail.next = node;
    }

    this.tail = node;
    this.length += 1;
  }

  pop() {
    const popItem = this.head;
    this.head = this.head.next;
    this.length -= 1;
    return popItem.item;
  }
}

const fs = require("fs");
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n");

const [N, M, K] = input.shift().split(" ").map(Number);
const board = input.map((v) => v.split(""));

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

const q = new Queue();
let visited = Array.from(Array(N), () =>
  Array.from(Array(M), () => Array(K + 1).fill(0))
);

visited[0][0][0] = 1;
q.push([0, 0, 0, 1]);

let answer = Infinity;
while (q.length > 0) {
  const [x, y, cnt, dist] = q.pop();

  if (x == N - 1 && y == M - 1) {
    answer = Math.min(answer, dist);
  }

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

    if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue;

    if (!visited[nx][ny][cnt] && board[nx][ny] == "0") {
      visited[nx][ny][cnt] = true;
      q.push([nx, ny, cnt, dist + 1]);
    } else if (!visited[nx][ny][cnt + 1] && board[nx][ny] == "1" && cnt < K) {
      visited[nx][ny][cnt + 1] = true;
      q.push([nx, ny, cnt + 1, dist + 1]);
    }
  }
}

if (answer == Infinity) console.log(-1);
else console.log(answer);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함