백준 2178번 - 미로탐색 (Sliver 1, JS, DFSBFS)
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [n,m] = input[0].split(' ');
const maps = [...input.slice(1).map((map) => map.trim().split('').map(v => +v))];
function solution(n, m, maps) {
let visited = [...maps].map((r) => r.map((c) => 1));
let queue = [[0, 0]];
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
while (queue.length > 0) {
let [x, y] = queue.shift();
for (let j = 0; j < 4; j++) {
nx = x + dx[j];
ny = y + dy[j];
if ( nx >= 0 && nx < n && ny >= 0 && ny < m ){
if(maps[nx][ny] === 1 && visited[nx][ny] === 1){
visited[nx][ny] = visited[x][y] + 1;
queue.push([nx,ny]);
}
}
}
}
return visited[n-1][m-1] === 1 ? -1 : visited[n-1][m-1];
}
console.log(solution(n, m, maps));
const fs=require('fs');
const input=fs.readFileSync('/dev/stdin').toString().split('\n');
const [n,m]=input[0].split(' ').map(el=>+el);
let map=input.slice(1,n+1).map(el=>el.split(''));
let queue=[];
queue.push([0,0,1]);
while(queue.length>0){
let [a,b,len]=queue.shift();
if(a===n-1&&b===m-1){
console.log(len);
break;
}else{
map[a][b]='0';
if(a<n-1&&map[a+1][b]==='1') queue.unshift([a+1,b,len+1]);
if(b<m-1&&map[a][b+1]==='1') queue.unshift([a,b+1,len+1]);
if(a>0&&map[a-1][b]==='1') queue.push([a-1,b,len+1]);
if(b>0&&map[a][b-1]==='1') queue.push([a,b-1,len+1]);
}
}