[프로그래머스] 게임 맵 최단거리 자바 풀이

2024. 3. 21. 16:29·알고리즘

문제

https://school.programmers.co.kr/learn/courses/30/lessons/1844?language=java

풀이

틀린 풀이

DFS를 통해 문제를 먼저 풀었지만 효율성 테스트에서 모두 실패했다.

새로운 풀이

문제점

DFS는 다음과 같은 문제가 있기 때문에 이 문제를 해결하는 방법으로 적합하지 않다.

  • 해가 없는 경로가 깊을 경우 탐색시간이 오래 걸릴 수 있다.
  • 얻어진 해가 최단 경로가 된다는 보장이 없다.

따라서, BFS로 다시 문제를 풀었다.

또한 맨날 헷갈리는 부분이 다익스트라(PQ)를 사용할 것인지 인데, PQ의 경우 가중치가 다른 경우에 사용한다는 것을 다시 기억하자.

일반적인 방법의 BFS를 통해 문제를 해결할 수 있다.

코드

package com.company.programmers;

import java.util.LinkedList;
import java.util.Queue;

public class P4 {
    static int[] dy = new int[] {-1,1,0,0};
    static int[] dx = new int[] {0,0,-1,1};
    static int[][] map;
    static boolean[][] visited;
    static int min = Integer.MAX_VALUE;
    public int solution(int[][] maps) {
        map = maps;

        visited = new boolean[maps.length][maps[0].length];
        visited[0][0] = true;
        bfs();
        if (min == Integer.MAX_VALUE) min = -1;
        return min;
    }
    public static void bfs() {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{0,0,1});
        while (!queue.isEmpty()) {
            int[] val = queue.poll();

            if (val[0] == map.length - 1  && val[1] == map[0].length - 1) {
                min = Math.min(val[2], min);
                return;
            }
            for (int i = 0; i < 4; i++) {
                int ny = val[0] + dy[i];
                int nx = val[1] + dx[i];

                if (ny < 0 || nx < 0 || ny >= map.length || nx >= map[0].length) continue;
                if (visited[ny][nx]) continue;
                if (map[ny][nx] == 0) continue;
                visited[ny][nx] = true;
                queue.add(new int[] {ny,nx,val[2]+1});
            }
        }

    }
    public static void main(String[] args) {
        P4 p4 = new P4();
        p4.solution(new int[][] {{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}});

    }

}

'알고리즘' 카테고리의 다른 글

[프로그래머스] 베스트 앨범 자바 풀이  (1) 2024.03.25
[프로그래머스] 메뉴 리뉴얼 자바 풀이  (0) 2024.03.20
[프로그래머스] PCCP 기출문제 4번 / 수레 움직이기 자바 풀이  (0) 2024.03.15
[백준] 1091 카드 섞기 자바 풀이  (0) 2024.03.14
[백준] 1360번 되돌리기 자바 풀이  (0) 2024.03.13
'알고리즘' 카테고리의 다른 글
  • [프로그래머스] 베스트 앨범 자바 풀이
  • [프로그래머스] 메뉴 리뉴얼 자바 풀이
  • [프로그래머스] PCCP 기출문제 4번 / 수레 움직이기 자바 풀이
  • [백준] 1091 카드 섞기 자바 풀이
HWBB
HWBB
흥미주도개발자
  • HWBB
    코딩공부방
    HWBB
  • 전체
    오늘
    어제
    • 분류 전체보기 (161)
      • 알고리즘 (61)
      • Android (27)
      • Kotlin (0)
      • Java (2)
      • Design Pattern (2)
      • React Native (1)
      • Python (0)
      • TIL (20)
      • Unity (0)
      • React (2)
      • AWS (0)
      • Git (11)
      • MFC (1)
      • Spring (4)
      • Computer Science (4)
      • Vue (4)
      • Infra (4)
      • 박현우 (10)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 승윤이
  • 공지사항

  • 인기 글

  • 태그

    깃허브
    Kotlin
    algorithm
    baekjoon
    programmers
    Android
    코딩테스트
    프로그래머스
    코틀린
    coding
    안드로이드
    안드로이드 스튜디오
    알고리즘
    백준
    C++
    GIT
    Java
    자바
    github
    android studio
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
HWBB
[프로그래머스] 게임 맵 최단거리 자바 풀이
상단으로

티스토리툴바