728x90
문제
https://www.acmicpc.net/problem/1261
문제 해석
이 문제는 지금까지와는 다르게 우선순위가 있는 길 찾기이다.
최대한 벽을 부수지 않고 이동해야하기 때문에 queue에 추가할 때 벽이 없는 길을 unshift를 이용해 queue 앞에 추가해 주고
벽이 있는 경우에는 기존과 같이 push를 이용해 queue 뒤에 추가하면 된다.
풀이
const filePath = process.platform === "linux" ? "dev/stdin" : "../test.txt";
const input = require("fs").readFileSync(filePath).toString().trim().split("\n");
const solution = (input) => {
const [n, m] = input.shift().split(" ").map(Number);
const table = input.map((e) => e.split("").map(Number));
const visited = Array.from(Array(m), () => Array(n).fill(0));
const dx = [-1, 0, 1, 0];
const dy = [0, 1, 0, -1];
const queue = [];
visited[0][0] = 1;
queue.push([0, 0, 0]);
while (queue.length) {
const [x, y, cnt] = queue.shift();
if (x === m - 1 && y === n - 1) {
return cnt;
}
for (let i = 0; i < 4; i++) {
let nx = x + dx[i];
let ny = y + dy[i];
if (nx < 0 || ny < 0 || nx >= m || ny >= n) continue;
if (table[nx][ny] === 0 && !visited[nx][ny]) {
visited[nx][ny] = 1;
queue.unshift([nx, ny, cnt]);
}
if (table[nx][ny] === 1 && !visited[nx][ny]) {
visited[nx][ny] = 1;
queue.push([nx, ny, cnt + 1]);
}
}
}
};
console.log(solution(input));
끝
728x90
'WEB > 백준 문제 풀이' 카테고리의 다른 글
백준 15723 n단 논법 (node.js) (0) | 2024.06.28 |
---|---|
백준 11403 경로 찾기 (node.js) (0) | 2024.06.27 |
백준 16987 계란으로 계란치기 (node.js) (0) | 2024.06.24 |
백준 15686 연산자 끼워 넣기 (node.js) (0) | 2024.06.22 |
백준 15686 치킨 배달 (node.js) (0) | 2024.06.20 |