프로그래머스 연습문제 - 게임 맵 최단거리 (level2, JS, DFSBFS)
실패..
// solution 1
function solution(maps) {
let answer = 1;
let visited = maps;
let queue = [];
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
const n = maps.length;
const m = maps[0].length;
queue.push([0, 0]);
visited[0][0] = 0;
while (queue.length > 0) {
let size = queue.length;
for (let i = 0; i < size; i++) {
let [x, y] = queue.shift();
for (let j = 0; j < 4; j++) {
let nx = x + dx[j];
let ny = y + dy[j];
if (nx >= 0 && nx < n && ny >= 0
&& ny < m && visited[nx][ny] === 1) {
if (nx == n - 1 && ny == m - 1) {
return ++answer;
}
queue.push([nx, ny]);
visited[nx][ny] = 0;
}
}
}
answer++;
}
return -1;
}
// solution 2
function solution(maps) {
const n = maps.length;
const m = maps[0].length;
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];
}