PS/Programmers
[Programmers] Level 2 : 게임 맵 최단거리
뱃싸공
2022. 12. 8. 14:40
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
{1, 1}에서 출발한 뒤 {N, M}에 도달할 수 있는 최소 비용을 구하라고 한다.
간선의 가중치는 1이므로 BFS나 DFS로 풀린다. Queue 문법에 좀 익숙해지려고 BFS로 풀었는데, 크게 고려할 점이 없어서 단순 구현만으로도 풀리는 문제이다.
import java.util.*;
class Solution {
private int[] dx = {0, 0, -1, 1};
private int[] dy = {1, -1, 0, 0};
private Queue<int[]> q = new LinkedList<>();
private int[][] visited = new int[110][110];
public int solution(int[][] maps) {
int answer = 0;
for (int i=0; i<110; i++) for(int j=0; j<110; j++) visited[i][j] = -1;
q.add(new int[]{0, 0});
visited[0][0] = 1;
while (!q.isEmpty()) {
int[] current = q.peek();
q.remove();
for (int i=0; i<4; i++) {
int nx = current[0] + dx[i];
int ny = current[1] + dy[i];
if(nx < 0 || ny < 0 || nx >= maps.length || ny >= maps[0].length) continue;
if(maps[nx][ny] == 0 || visited[nx][ny] != -1) continue;
visited[nx][ny] = visited[current[0]][current[1]] + 1;
q.add(new int[]{nx, ny});
}
}
return visited[maps.length-1][maps[0].length-1];
}
}