프로그래머스 DFS/BFS 게임 맵 최단거리

jaegeunsong97·2023년 2월 27일
0
post-thumbnail



보고 BFS 방식을 푸는 것이라고 생각했지만, 아직 구현은 되지 않았다.

그리고 보니까 이코테의 미로찾기 문제와 매우 유사하다.

하지만 안에 함수를 bfs로 따로 빼서 구현하고 싶은데 하는 방법을 모르겠다.

그래도 일단 코드의 해설을 자세하게 적었으니 다음번에는 이해할 수 있을 것 같다.

import java.util.*;

class Node{
        private int x;
        private int y;

        public Node(int x, int y){
            this.x = x;
            this.y = y;
        }

        public int getX(){
            return this.x;
        }

        public int getY(){
            return this.y;
        }
    }

class Solution {
	// 방향 벡터
    public static int[] dx = {0, 1, 0, -1};
    public static int[] dy = {-1, 0, 1, 0};

    public int solution(int[][] maps) {
        Queue<Node> q = new LinkedList<>();
        int x = 0;
        int y = 0;

        q.offer(new Node(x, y)); // 초기값 세팅

        while(!q.isEmpty()){
            Node now = q.poll(); // 1개를 꺼내서 x y 가져오기
            x = now.getX();
            y = now.getY();

            for(int i = 0 ; i < 4; i++){ // 방향 벡터의 길이만큼 순회

                int nx = x + dx[i];
                int ny = y + dy[i];
                
                // 다음 좌표가 map안에 포함, 다음 위치에 방문 안한 경우
                if(0 <= nx && nx < maps[0].length && 0 <= ny && 
                ny < maps.length && maps[ny][nx] == 1) {
                    
                    maps[ny][nx] = maps[y][x] + 1; // 이전까지 누적합
                    q.offer(new Node(nx, ny)); // 다음 좌표를 큐에 넣어줌
                }
            }
        }
        int answer = maps[maps.length - 1][maps[0].length - 1]; // 마지막 위치 저장
        return (answer == 1) ? -1 : answer; // 도달 X (-1) || 도달 O (answer)
    }
}
profile
현재 블로그 : https://jasonsong97.tistory.com/

0개의 댓글