티스토리 뷰
{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];
}
}
'PS > Programmers' 카테고리의 다른 글
[Programmers] Level 2 : 영어 끝말잇기 (0) | 2022.12.12 |
---|---|
[Programmers] Level 2 : 베스트앨범 (0) | 2022.12.08 |
[Programmers] Level 2 : 모음사전 (0) | 2022.12.08 |
[Programmers] Level 2 : 귤 고르기 (1) | 2022.12.08 |
[Programmers] Level 2 : 스킬트리 (0) | 2022.12.08 |