코테/프로그래머스

[프로그래머스/Lv. 2] 게임 맵 최단거리 (JAVA)

imname1am 2023. 9. 14. 12:56
반응형

🔺 문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

🔺 코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.*;
import java.io.*;
 
class Solution {
    static int[] dx = {0,0,-1,1};
    static int[] dy = {1,-1,0,0};
    
    static int[][] maps, dist;
    static boolean[][] visited;
    static int answer = 0;
    
    static int row, col;
    
    public int solution(int[][] maps) {
        this.maps = maps;
        
        row = maps.length;
        col = maps[0].length;
        
        dist = new int[row + 1][col + 1];
        visited = new boolean[row + 1][col + 1];
        
        bfs(00);    // (0,0) 에서 BFS 한 번만 수행
 
        return answer;
    }
    
    private static void bfs(int a, int b) {
        visited[a][b] = true;
        
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] {a, b});
        
        while(!q.isEmpty()) {
            int[] now = q.poll();
            
            for(int d = 0 ; d < 4 ; d++) {
                int x = now[0+ dx[d];
                int y = now[1+ dy[d];
                
                if(x < 0 || y < 0 || x >= row || y >= col) continue;
                if(visited[x][y] || maps[x][y] == 0continue;
                
                if(!visited[x][y] && maps[x][y] == 1) {
                    visited[x][y] = true;
                    dist[x][y] = dist[now[0]][now[1]] + 1;
                    q.add(new int[] {x, y});
                }
            }
        }
        
        answer = (dist[row - 1][col - 1== 0) ? - 1 : (dist[row - 1][col - 1+ 1);
    }
}
cs
✅ 해결 아이디어
BFS
: 최단 거리 구하는 거니까 BFS로 풀었다.
(0,0)에서 상하좌우 탐색하면서, 이동 가능한 칸 발견 시 큐에 추가하고, 거리 배열을 갱신하며 이동한다.

마지막 칸의 값이 0이면 마지막 칸에 도달하지 못 한 것이므로 -1을 출력하고,
그게 아니라면 거리 배열의 마지막 칸 값을 출력한다.

 

 


🔺 다른 풀이들

- 나처럼 방문 배열과 거리 배열을 따로 둘 필요 없이, 아래 코드처럼 방문 겸 거리 배열 하나만 작성해서 해도 된다!

 

[프로그래머스] 게임 맵 최단거리(Java 자바)

https://programmers.co.kr/learn/courses/30/lessons/1844 코딩테스트 연습 - 게임 맵 최단거리 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1 programmers.co.kr 문

tmdrl5779.tistory.com

 

 

- 깔끔하시다... 상하좌우도 향상형 for문 쓰심!

큐에 파라미터로 시작 위치와 거리를 함께 가져가시면서 거리를 갱신하심

import java.util.*;

class Solution {
    public int solution(int[][] maps) {
        int rows = maps.length;
        int cols = maps[0].length;

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 상하좌우

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0, 1}); // 시작 위치와 거리

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int row = current[0];
            int col = current[1];
            int distance = current[2];

            if (row == rows - 1 && col == cols - 1) {
                return distance; // 목적지에 도달한 경우 최단거리 반환
            }

            for (int[] dir : directions) {
                int newRow = row + dir[0];
                int newCol = col + dir[1];

                if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && maps[newRow][newCol] == 1) {
                    maps[newRow][newCol] = 0; // 방문한 위치는 재방문하지 않도록 표시
                    queue.offer(new int[]{newRow, newCol, distance + 1});
                }
            }
        }

        return -1; // 목적지에 도달하지 못한 경우
    }
}

💬 느낀 점

이런 문제만 나오면 좋겠구나,,,,하하하ㅏ

 

 

1회독 2회독 3회독 4회독 5회독
V        

 

반응형