강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

youngyou1324님의 프로필 이미지
youngyou1324

작성한 질문수

자바 코딩테스트 - it 대기업 유제

4. "미로의 최단거리 통로(L 탐색)" 문제 해법

미로의 최단거리 통로

작성

·

56

0

안녕하세요 혹시 이 문제를 풀 때 꼭 dist배열을 만들어야 될까요? 제 코드를 아래 보여드립니다.

바로 L를 반환하게 만들었는데 이래도 괜찮을지요?

 

package org.youyk.inflearn.latest.sec07.Problem4;

import java.util.*;
class Solution1 {
    static int[] dx = {0,0,-1,1};
    static int[] dy = {1,-1,0,0};
    public int solution(int[][] board){
        int answer = 0;
        int[][] ch = new int[board.length][board[0].length];
        Queue<int[]> queue =new LinkedList<>();
        int n = board.length;
        int m = board[0].length;

        queue.add(new int[]{0,0});
        ch[0][0] = 1;
        int L=0;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                int[] poll = queue.poll();

                if(poll[0] == n-1 && poll[1] == m-1){
                    return L;
                }
                for(int j=0;j<4;j++){
                    int xx = dx[j] + poll[0];
                    int yy = dy[j] + poll[1];

                    if(xx>=0 && yy>=0 && xx<n && yy<m && board[xx][yy] ==0){
                        board[xx][yy] = 1;
                        queue.add(new int[]{xx,yy});
                    }
                }
            }
            L++;
        }

        return -1;
    }

    public static void main(String[] args){
        Solution1 T = new Solution1();
        int[][] arr={{0, 0, 0, 0, 0, 0, 0},
                     {0, 1, 1, 1, 1, 1, 0},
                     {0, 0, 0, 1, 0, 0, 0},
                     {1, 1, 0, 1, 0, 1, 1},
                     {1, 1, 0, 1, 0, 0, 0},
                     {1, 0, 0, 0, 1, 0, 0},
                     {1, 0, 1, 0, 0, 0, 0}};

        int[][] arr3={{0, 0, 1, 1, 1, 1, 1},
                      {0, 0, 1, 0, 0, 0, 0},
                      {1, 0, 1, 0, 0, 0, 0},
                      {0, 0, 1, 1, 0, 0, 0},
                      {1, 0, 0, 0, 0, 1, 0},
                      {0, 0, 1, 0, 0, 1, 0},
                      {0, 0, 1, 1, 1, 0, 0}};

        int[][] arr2={{1, 0, 0, 0, 1, 0, 0},
                {0, 1, 1, 1, 1, 1, 0},
                {0, 0, 0, 1, 0, 0, 0},
                {1, 1, 0, 1, 1, 1, 1},
                {1, 1, 0, 1, 0, 0, 0},
                {1, 0, 0, 0, 1, 0, 0},
                {1, 0, 1, 0, 1, 0, 0}};
        System.out.println(T.solution(arr));
        System.out.println(T.solution(arr2));
        System.out.println(T.solution(arr3));
    }
}

답변 1

0

김태원님의 프로필 이미지
김태원
지식공유자

안녕하세요^^

네. dist 배열을 사용하지 않고, 레벨값인 L을 바로 리턴해도 됩니다.

youngyou1324님의 프로필 이미지
youngyou1324

작성한 질문수

질문하기