[프로그래머스] 1844 게임 맵 최단거리 - JAVA - Lv.2

2025. 4. 14. 16:41·알고리즘/문제풀이

[프로그래머스] 1844 게임 맵 최단거리 - JAVA - Lv.2

문제

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

문제 분석

조건

  • n*m 사이즈로 주어진 맵에서 0,0(문제에선 1,1) 좌표에서 n-1, m-1(n, m) 좌표로 이동하는데 최단 거리를 구하는 문제이다.

풀이방법

  • 최단거리를 구하는 문제이므로 bfs의 가장 기본적인 문제이다.
  • 거쳐간 땅의 수를 구해야하는 문제이므로 간단하게 좌표와 카운트를 변수로 가지는 Node 클래스를 만들어 문제를 해결했다.
  • 처음 있던 위치부터 카운트해야하므로 초기 카운트가 1부터 시작한다.

코드

import java.util.*;

class Solution {
    public int solution(int[][] maps) {
        int[][] dr = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        int goalR = maps.length;
        int goalC = maps[0].length;
        boolean[][] visited = new boolean[goalR][goalC];
        goalR--;
        goalC--;

        Deque<Node> que = new ArrayDeque<>();
        que.add(new Node(0, 0, 1));
        visited[0][0] = true;

        while (!que.isEmpty()) {
            Node now = que.pop();
            if (now.getR() == goalR && now.getC() == goalC) {
                return now.getCount();
            }
            for (int[] d : dr) {
                int nextR = now.getR() + d[0];
                int nextC = now.getC() + d[1];
                if (nextR >= 0 && nextR <= goalR && nextC >= 0 && nextC <= goalC) {
                    if (maps[nextR][nextC] == 0 || 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, 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
저작자표시 비영리 변경금지 (새창열림)
'알고리즘/문제풀이' 카테고리의 다른 글
  • [백준/BOJ] 2606 바이러스 - JAVA - 실버3
  • [프로그래머스] 159993 미로 탈출 - JAVA - Lv.2
  • [프로그래머스] 72413 합승 택시 요금 - JAVA - Lv.3
  • [백준/BOJ] 9328 열쇠 - JAVA
LIRI
LIRI
  • LIRI
    기록
    LIRI
  • 전체
    오늘
    어제
    • 분류 전체보기 (74)
      • 블로그 꾸미기 (0)
      • Spring (6)
      • 바이브코딩 (1)
      • React (3)
      • CS (0)
      • 알고리즘 (57)
        • 개념 (2)
        • 문제풀이 (54)
      • Java (1)
      • DB (1)
      • log (4)
        • SSAFY (3)
        • 궁금 (1)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 공지사항

  • 인기 글

  • 태그

    Java
    커서ai
    Security
    LV2
    그리디
    JWT
    Spring
    느좋코딩
    pccp모의고사
    LIS
    dp
    springboot
    알고리즘 문제풀이
    lv3
    dfs
    리액트
    SSAFY 9기
    알고리즘
    ssafy 합격 후기
    BFS
    프로그래머스
    백준
    최장증가부분수열
    SSAFY
    바이브코딩
    비트마스킹
    너비우선탐색
    BOJ
    싸피
    Springsecurity
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
LIRI
[프로그래머스] 1844 게임 맵 최단거리 - JAVA - Lv.2
상단으로

티스토리툴바