티스토리 뷰

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

 

14940번: 쉬운 최단거리

지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000) 다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이

www.acmicpc.net

let input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n').map(v => v.split(' ').map(Number))
const [N, M] = input.shift();

let start;
for (let i = 0; i < N; i++) {
	for (let j = 0; j < M; j++) {
		if (input[i][j] == 1) {
			input[i][j] = -1;

		} else if (input[i][j] == 2) {
			input[i][j] = 0;
			start = [i, j];
		}
	}
}

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 dx = [0, 0, -1, 1];
const dy = [-1, 1, 0, 0];

const q = new Queue();

q.push(start);

while (q.length > 0) {
	const [x, y] = q.pop();
	const dist = input[x][y];
	for (let k = 0; k < 4; k++) {
		const nx = x + dx[k];
		const ny = y + dy[k];

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

		if (input[nx][ny] == -1 || input[nx][ny] > dist + 1) {
			input[nx][ny] = dist + 1;
			q.push([nx, ny])
		}
	}
}
console.log(input.map(v => v.join(' ')).join('\n'))
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
글 보관함