프로그래머스

프로그래머스 미로 탈출 - 자바(java)

리콜 2024. 5. 9. 23:22

https://school.programmers.co.kr/learn/courses/30/lessons/159993

 

프로그래머스

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

programmers.co.kr

 

 

최소 거리를 구하는 문제이기 때문에 bfs로 

시작지점에서 레버까지의 거리와 레버에서 종료지점까지의 거리를 더하는 방법으로 문제를 풀었다.

import java.util.LinkedList;
import java.util.Queue;
import java.awt.Point;
import java.util.Arrays;

class Solution {
    //시작 지점, 출구, 레버 저장하고 
    // bfs로 최단 거리
    public static char[][] map ;
    public static boolean[][] check;
    public static int[][] mapCount;
    public int solution(String[] maps) {
        int x ,y;
        Point S = new Point(0,0), E = new Point(0,0), L = new Point(0,0);
        map = new char[maps.length][maps[0].length()];
        check = new boolean[maps.length][maps[0].length()];
        mapCount = new int[maps.length][maps[0].length()];  
        
        
        
        for(int i =0; i<maps.length;i++){
            for(int j =0; j<maps[0].length();j++){
                map[i][j] = maps[i].charAt(j);
                if(maps[i].charAt(j) == 'S'){
                    S = new Point(i,j);
                }
                else if(maps[i].charAt(j) == 'E'){
                    E = new Point(i,j);
                }
                else if(maps[i].charAt(j) == 'L'){
                    L = new Point(i,j);
                }
            }
        }
        
        int toLever = bfs(S, L);
        for(int i =0;i<mapCount.length;i++){
            Arrays.fill(mapCount[i], 0);
            Arrays.fill(check[i],false);
        }
        
        int toEnd = bfs(L, E);
        
        if(toLever == -1 || toEnd == -1){
            return -1;
        }
        int answer = toLever + toEnd;
        return answer;
    }
    
    public int bfs(Point start, Point end){
        Queue<Point> queue = new LinkedList<>();
        queue.add(start);
        check[start.x][start.y] = true;
        mapCount[start.x][start.y] = 0;
        
        int[] dx = {1, -1 , 0,0};
        int[] dy = {0,0,1,-1};
        while(!queue.isEmpty()){
            Point current = queue.poll();
            
            if(current.equals(end)){
                return mapCount[current.x][current.y];
            }
            
            for(int i = 0; i < 4; i++){
                int nextX = current.x + dx[i];
                int nextY = current.y + dy[i];
                
                if(nextX >= 0 && nextX < map.length && nextY >= 0 && nextY < map[0].length
                   && map[nextX][nextY] != 'X' && check[nextX][nextY] == false)
                {
                    queue.add(new Point(nextX, nextY));
                    check[nextX][nextY] = true;
                    mapCount[nextX][nextY] += mapCount[current.x][current.y] + 1;
                }
                
                
            }
            
        }
        return -1;
        
    }
}
반응형