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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

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

const [N, M] = input.shift().split(" ").map( i => Number(i));
const maps = [];
const vector = [[0,1], [1,0], [0,-1], [-1,0]];

input.forEach((i) => {
   i = i.split("").map(d => Number(d));
   maps.push(i);
});

const bfs = () => {
    const queue = [[0,0]];

    while(queue.length) {
        const cur = queue.shift();

        if(maps[cur[0]][cur[1]] !== 0) {
            const vectors = [];

            vector.forEach((v) => {
                const x = cur[0]+v[0];
                const y = cur[1]+v[1];

                if(x >= 0 && y >= 0 && x < N && y < M && maps[x][y] === 1) {
                    vectors.push([x,y]);
                }
            });

            let prev = maps[cur[0]][cur[1]];

            vectors.forEach((v) => {
                maps[v[0]][v[1]] = prev+1;
            })

            queue.push(...vectors);
        }
    }

    return maps[N-1][M-1];
}


console.log(bfs());
728x90

+ Recent posts