[프로그래머스] 1844 / 게임 맵 최단거리

maxxyoung·2022년 7월 25일
0

문제

ROR 게임은 두 팀으로 나누어서 진행하며, 상대 팀 진영을 먼저 파괴하면 이기는 게임입니다. 따라서, 각 팀은 상대 팀 진영에 최대한 빨리 도착하는 것이 유리합니다.

게임 맵의 상태 maps가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1을 return 해주세요.

제한사항

  • maps는 n x m 크기의 게임 맵의 상태가 들어있는 2차원 배열로, n과 m은 각각 1 이상 100 이하의 자연수입니다.
  • n과 m은 서로 같을 수도, 다를 수도 있지만, n과 m이 모두 1인 경우는 입력으로 주어지지 않습니다.
  • maps는 0과 1로만 이루어져 있으며, 0은 벽이 있는 자리, 1은 벽이 없는 자리를 나타냅니다.
  • 처음에 캐릭터는 게임 맵의 좌측 상단인 (1, 1) 위치에 있으며, 상대방 진영은 게임 맵의 우측 하단인 (n, m) 위치에 있습니다.

문제풀이

이렇게 예시가 많은 문제는 내가 생각하지 못한 조건이 반드시 숨어있으므로 모든 조건을 필수적으로 다 분석해야함.

package programmers.dfsbfs;

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

public class Q1844 {
    public static void main(String[] args) {
        int[][] maps = new int[5][5];
        maps[0] = new int[]{1, 0, 1, 1, 1};
        maps[1] = new int[]{1, 0, 1, 0, 1};
        maps[2] = new int[]{1, 0, 1, 1, 1};
        maps[3] = new int[]{1, 1, 1, 0, 1};
        maps[4] = new int[]{0, 0, 0, 0, 1};
        System.out.println(solution(maps));

    }

    public static int solution(int[][] maps) {
        int h, w, answer;
        h = maps.length;
        w = maps[0].length;
        int[][] visited = new int[h][w];
        for (int i = 0; i < maps.length; i++) {
            Arrays.fill(visited[i], 0);
        }
        //bfs로 경로를 탐색 후, visited n-1,m-1자리를 방문하지 않았으면 return -1
        int shortcutCount = bfs(new Location(0, 0), maps,visited, h, w);
        if(shortcutCount == 0){
            answer = -1;
        } else {
            answer = shortcutCount;
        }
        return answer;
    }

    public static int bfs(Location location,int[][] maps,int[][] visited,int h, int w){
        //큐와 오퍼레이터
        int[] rowOp = new int[]{1, -1, 0, 0};
        int[] columnOp = new int[]{0, 0, 1, -1};
        Queue<Location> q = new LinkedList<>();
        q.add(location);
        visited[location.row][location.column] = 1;

        //while문
        while (!q.isEmpty()) {
            Location curLocation = q.poll();
            for (int i = 0; i < 4; i++) {
                int nextRow = curLocation.row + rowOp[i];
                int nextColumn = curLocation.column+ columnOp[i];
                //큐에서 하나 꺼내, 루프 돌며,범위 안이고, 벽이 아니고, 방문하지 않은 곳이면 방문
                if((nextRow>=0&&nextColumn>=0&&nextRow<h&&nextColumn<w)
                    && maps[nextRow][nextColumn] == 1
                    && visited[nextRow][nextColumn] == 0){
                    //큐에 넣어주고, visited에 depth 표시
                    q.add(new Location(nextRow, nextColumn));
                    visited[nextRow][nextColumn] = visited[curLocation.row][curLocation.column] + 1;
                }
            }
        }
        return visited[h - 1][w - 1];
    }

    public static class Location{
        int row;
        int column;

        public Location(int row, int column) {
            this.row = row;
            this.column = column;
        }
    }
}
profile
오직 나만을 위한 글. 틀린 부분 말씀해 주시면 감사드립니다.

0개의 댓글

관련 채용 정보