[Programmers] 게임 맵 최단거리

2024. 9. 12. 13:23·Algorithm/문제풀이

❒ Description


제목 게임 맵 최단거리
링크 https://school.programmers.co.kr/learn/courses/30/lessons/1844
자료구조/알고리즘 Map, Queue / 넓이 우선 탐색(BFS)
시간 복잡도 O(row수 * col수) 

 

BFS를 사용해서 해결 할 수 있는 문제이다. 문제의 핵심 포인트는 maps[row][col] 값을 업데이트 해주는 부분이다.

시간 복잡도의 경우는 모든 노드를 한 번씩 방문하기 때문에 O(N*M)의 시간 복잡도를 갖는다.

 

 

 

 

 

❒ Solution


더보기
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    private final int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    private int maxCol;
    private int maxRow;
    private boolean[][] visited;

    public int solution(int[][] maps) {
        maxRow = maps.length;
        maxCol = maps[0].length;
        visited = new boolean[maxRow][maxCol];
        bfs(maps);
        boolean isVisitedEnemyHQ = visited[maxRow - 1][maxCol - 1];
        int enemyHQ = maps[maxRow - 1][maxCol - 1];
        return isVisitedEnemyHQ ? enemyHQ : -1;
    }

    public void bfs(int[][] maps) {
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{0, 0});
        visited[0][0] = true;
        while (!q.isEmpty()) {
            int[] cur = q.remove();
            int curRow = cur[0];
            int curCol = cur[1];

            for (int[] dir : dirs) {
                int nextRow = curRow + dir[0];
                int nextCol = curCol + dir[1];
                if (isInRange(nextRow, nextCol, maps) && isVisitable(nextRow, nextCol, maps)) {
                    visited[nextRow][nextCol] = true;
                    // ※ 방문 후 maps 값 업데이트
                    maps[nextRow][nextCol] = maps[curRow][curCol] + 1;
                    q.offer(new int[]{nextRow, nextCol});
                }
            }
        }
    }

    private boolean isInRange(int nextRow, int nextCol, int[][] maps) {
        return nextRow >= 0 && nextRow < maxRow && nextCol >= 0 && nextCol < maxCol;
    }
    
    private boolean isVisitable(int nextRow, int nextCol, int[][] maps) {
        return !visited[nextRow][nextCol] && maps[nextRow][nextCol] != 0;
    }
}

 

bfs 메소드에서 필요한 validation이 너무 많아서 isInRange와 isVisitable 메소드를 추출하였다.

 

 

 

 

 


 

'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#743] Network Delay Time  (0) 2024.09.15
[Programmers#49191] 순위  (0) 2024.09.14
[LeetCode#787] Cheapest Flights Within K Stops  (0) 2024.09.10
[LeetCode#207] Course Schedule  (0) 2024.08.30
[LeetCode#46] Permutation  (0) 2024.08.21
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#743] Network Delay Time
  • [Programmers#49191] 순위
  • [LeetCode#787] Cheapest Flights Within K Stops
  • [LeetCode#207] Course Schedule
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (207)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (6)
        • Java (3)
        • Kotlin (3)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (39)
        • 친절한 SQL 튜닝 (9)
        • 데이터 중심 애플리케이션 설계 (14)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • Spring Batch docs (10)
        • Quartz docs (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    부분단조성
    Two-Pointer
    binarysearch
    Back-Tracking
    오블완
    sliding-window
    greedy
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[Programmers] 게임 맵 최단거리
상단으로

티스토리툴바