Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 그리디
- 2164 자바
- 백준 10866 자바
- dfs
- 2346 풍선 터뜨리기
- 백준 2346 자바
- 백준
- 10813 자바
- 28278 스택 2
- 2748 자바
- 자바 2164
- 자바
- 백준 1764 자바
- 2798 자바
- BFS
- 파이썬
- 10807 자바
- IAM Identity Center
- 자바 1003
- IAM 사용자
- 자바 2346
- 자바 28278
- 백준 28278 자바
- 코딩테스트
- 자바 10866
- 데보션영 3기
- 1010 자바
- 1764 자바
- 티움투어
- 10810 자바
Archives
- Today
- Total
자두의 데브로그
[자바] 프로그래머스 게임 맵 최단거리 본문
https://school.programmers.co.kr/learn/courses/30/lessons/1844
미로 게임이랑 거의 유사하지만 만약 가는 길이 없으면 가장 마지막에 -1로 출력해야되는 부분이 달랐다. 최단 거리를 구하는 문제이기 때문에 bfs를 구현해서 풀면 됐었는데, bfs의 for문 내에서 queue에 값을 추가해야하는 것을 까먹고 재귀로 넣어서 첫 번째 풀이는 틀렸었다. 탐색을 시작하는 지점은 (0, 0) 좌표이기 때문에 애초에 bfs(0, 0)을 실행하면 된다. visited[0][0]은 bfs 함수를 처음 실행하기 전에 true로 만들어주고 bfs 내부에서 방문할 때 true로 바꿔주면 된다.
import java.util.*;
class Solution {
static int[][] graph;
static boolean[][] visited;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
public int solution(int[][] maps) {
graph = maps;
visited = new boolean[maps.length][maps[0].length];
visited[0][0] = true;
bfs(0, 0);
int answer = -1;
if(graph[maps.length - 1][maps[0].length - 1] != 1){
answer = graph[maps.length - 1][maps[0].length - 1];
}
return answer;
}
public static void bfs(int x, int y){
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{x, y});
while(!queue.isEmpty()){
int[] now = queue.poll();
int now_x = now[0];
int now_y = now[1];
visited[now_x][now_y] = true;
for(int i = 0; i < 4; i++){
int next_x = now_x + dx[i];
int next_y = now_y + dy[i];
if(next_x < graph.length && next_y < graph[0].length && next_x >= 0 && next_y >= 0){
if(graph[next_x][next_y] == 1 && !visited[next_x][next_y]){
queue.add(new int[]{next_x, next_y});
visited[next_x][next_y] = true;
graph[next_x][next_y] = graph[now_x][now_y] + 1;
}
}
}
}
}
}
'코딩테스트 > 문제 풀이' 카테고리의 다른 글
[자바] 백준 1697번 숨바꼭질 (0) | 2024.08.27 |
---|---|
[자바] 백준 11725번 트리의 부모 찾기 (0) | 2024.08.26 |
[자바] 백준 2178번 미로 탐색 (0) | 2024.08.22 |
[자바] 백준 2667번 단지번호붙이기 (0) | 2024.08.21 |
[자바] 백준 1012번 유기농 배추 (0) | 2024.08.19 |