티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 2623번: 음악프로그램 (0) | 2023.07.07 |
---|---|
Node.js) 백준 17626번: Four Squares (0) | 2023.07.06 |
Node.js) 백준 18870번: 좌표 압축 (0) | 2023.07.06 |
Node.js) 백준 11659번: 구간 합 구하기 4 (0) | 2023.07.06 |
Node.js) 백준 1764번: 듣보잡 (0) | 2023.07.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 투포인터
- 다이나믹프로그래밍
- 면접질문
- 서버점검
- 서버개발
- MOD
- 로드나인
- 면접비
- 그래프
- MySQL
- 다이나밍프로그래밍
- create db
- create databases;
- 은둔청년체험
- 롱베케이션
- 투포인터 연습
- BFS
- 개발자면접
- 최소공통조상
- DB 생성
- 동적프로그래밍
- node.js
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함