문제
https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
DFS 풀이 (효율성 테스트 실패)
function solution(maps) {
const n = maps.length;
const m = maps[0].length;
const dy = [0, 1, 0, -1];
const dx = [1, 0, -1, 0];
let answer = -1;
const isVisited = Array(n)
.fill(false)
.map(() => Array(m).fill(false));
isVisited[0][0]=true;
dfs(0, 0, 1);
function dfs(y, x, cnt) {
if (y === n - 1 && x === m - 1) {
if (answer === -1 || answer > cnt) {
answer = cnt;
}
return;
}
for (let i = 0; i < 4; i++) {
const ny = y + dy[i];
const nx = x + dx[i];
if (inRange(ny, nx) && !isVisited[ny][nx]) {
isVisited[ny][nx] = true;
dfs(ny, nx, cnt + 1);
isVisited[ny][nx] = false;
}
}
}
function inRange(y, x) {
return 0 <= y && y < n && 0 <= x && x < m && maps[y][x] === 1;
}
return answer;
}
BFS 풀이
function solution(maps) {
const n = maps.length;
const m = maps[0].length;
const dy = [0, 1, 0, -1];
const dx = [1, 0, -1, 0];
const q = [];
q.push([0,0,1]);
while(q.length){
const [y,x,cnt] = q.shift();
if(y===n-1 && x===m-1) return cnt;
for(let i=0; i<4; i++){
const ny=y+dy[i];
const nx=x+dx[i];
if(inRange(ny,nx)){
maps[ny][nx]=0;
q.push([ny,nx,cnt+1]);
}
}
}
function inRange(y, x) {
return 0 <= y && y < n && 0 <= x && x < m && maps[y][x] === 1;
}
return -1
}
정리
최단 거리 문제는 BFS로 풀어야 효율성이 좋다!
참조
'Programmers' 카테고리의 다른 글
[프로그래머스] 불량 사용자 (JS) - DFS (1) | 2023.11.22 |
---|---|
[프로그래머스] 표 병합 - union find (1) | 2023.11.21 |
[프로그래머스] 수식 최대화 (JS) (1) | 2023.11.21 |
[프로그래머스] 튜플 (JS) (0) | 2023.11.20 |
[프로그래머스] 보석 쇼핑 (JS) - Map, 투포인터 (0) | 2023.11.20 |