[프로그래머스] 159993 미로 탈출 - JAVA - Lv.2

2025. 4. 15. 00:58·알고리즘/문제풀이

[프로그래머스] 159993 미로 탈출 - JAVA - Lv.2

문제

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

문제 분석

조건

  • 문자열로 주어진 `maps`에서 S좌표에서 L좌표로, 그후 E좌표로 이동하는 최단 거리를 구하는 문제이다.
  • 같은 좌표를 다시 지날 수 있으며 S좌표에서 L좌표로 이동할 때 E좌표를 지날 수 있다.
  • L좌표에서 E좌표로 이동할때도 S좌표를 지날 수 있다.
  • 1칸 이동할 때 1초가 걸릴때, 최단 시간을 구하기.

풀이방법

  • 최단거리를 구하는 문제이므로 bfs를 이용한다.
  • 좌표와 카운트를 변수로 가지는 Node 클래스를 만들어 문제를 해결했다.
  • bfs를 2번 이용하여 S>L, L>E 순으로 횟수를 구하였다.
  • L좌표에 도착하였다면 `visited`배열과 `que`를 초기화 해주었다.
    • L좌표에 가는 경로에 E좌표가 없었다면 `visited`를 초기화를 하지 않아도 되지만 채점 기준에 효율성 테스트가 없어서 따로 체크하지 않았다.

코드

import java.util.*;

class Solution {
    public int solution(String[] maps) {
        int answer = 0;
        char[][] map = new char[maps.length][maps[0].length()];
        boolean[][] visited = new boolean[map.length][map[0].length];

        Node start = null;
        Node lever = null;
        for (int r = 0; r < maps.length; r++) {
            for (int c = 0; c < maps[0].length(); c++) {
                map[r][c] = maps[r].charAt(c);
                if (map[r][c] == 'S') {
                    start = new Node(r, c, 0);
                    visited[r][c] = true;
                    map[r][c] = 'S';
                } else if (map[r][c] == 'L') {
                    lever = new Node(r, c);
                }
            }
        }
        Deque<Node> que = new ArrayDeque<>();
        que.add(start);
        answer += bfs(map, visited, que, 'L');
        if (answer == -1) {
            return answer;
        }
        visited = new boolean[map.length][map[0].length];
        visited[lever.getR()][lever.getC()] = true;
        que = new ArrayDeque<>();
        que.add(lever);
        int temp = bfs(map, visited, que, 'E');
        if (temp == -1) {
            return -1;
        }
        return answer + temp;
    }

    private static int bfs(char[][] map, boolean[][] visited, Deque<Node> que, char find) {
        int[][] dr = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!que.isEmpty()) {
            Node now = que.pop();
            if (map[now.getR()][now.getC()] == find) {
                return now.getCount();
            }
            for (int[] d : dr) {
                int nextR = now.getR() + d[0];
                int nextC = now.getC() + d[1];
                if (nextR >= 0 && nextR < map.length && nextC >= 0 && nextC < map[0].length) {
                    if (map[nextR][nextC] == 'X' || visited[nextR][nextC]) {
                        continue;
                    }
                    visited[nextR][nextC] = true;
                    que.add(new Node(nextR, nextC, now.getCount() + 1));
                }
            }
        }
        return -1;
    }
}

class Node {
    private int r;
    private int c;
    private int count;

    public Node(int r, int c) {
        this.r = r;
        this.c = c;
        this.count = 0;
    }

    public Node(int r, int c, int count) {
        this.r = r;
        this.c = c;
        this.count = count;
    }

    public int getR() {
        return r;
    }

    public int getC() {
        return c;
    }

    public int getCount() {
        return count;
    }
}

결과

728x90
저작자표시 비영리 변경금지 (새창열림)
'알고리즘/문제풀이' 카테고리의 다른 글
  • [프로그래머스] 43165 타겟 넘버 - JAVA - Lv.2
  • [백준/BOJ] 2606 바이러스 - JAVA - 실버3
  • [프로그래머스] 1844 게임 맵 최단거리 - JAVA - Lv.2
  • [프로그래머스] 72413 합승 택시 요금 - JAVA - Lv.3
LIRI
LIRI
  • LIRI
    기록
    LIRI
  • 전체
    오늘
    어제
    • 분류 전체보기 (73)
      • 블로그 꾸미기 (0)
      • Spring (6)
      • React (3)
      • CS (0)
      • 알고리즘 (57)
        • 개념 (2)
        • 문제풀이 (54)
      • Java (1)
      • DB (1)
      • log (4)
        • SSAFY (3)
        • 궁금 (1)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 공지사항

  • 인기 글

  • 태그

    BFS
    최장증가부분수열
    싸피
    알고리즘
    프로그래머스
    lv3
    비트마스킹
    알고리즘 문제풀이
    Security
    그리디
    dp
    불 끄기
    ssafy 합격 후기
    골드1
    LIS
    SSAFY 9기
    Spring
    도대체왜
    SSAFY
    BOJ
    너비우선탐색
    리액트
    백준
    Java
    pccp모의고사
    JWT
    springboot
    dfs
    LV2
    Springsecurity
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
LIRI
[프로그래머스] 159993 미로 탈출 - JAVA - Lv.2
상단으로

티스토리툴바