강의

멘토링

커뮤니티

Inflearn Community Q&A

lsh81552606's profile image
lsh81552606

asked

Introduction to Java Algorithm Problem Solving: Coding Test Preparation

15. Pizza Delivery Distance (DFS)

피자배달거리(DFS) 시간초과 질문 있습니다.

Written on

·

536

0

안녕하세요. 좋은 강의 만들어주셔서 덕분에 알고리즘 공부를 수월하게 하고 있습니다.

다름이 아니라, 문제 풀이하는 방법은 강의와 유사하게 하였습니다.
저는 DFS를 활용할 때 선택된 피자가게의 index가 아닌, 객체 자체를 selected 배열에 넣는 방식으로 진행하였습니다. 예제와 똑같은 출력값이 나왔으나, 시간 초과라고 하여서 강의와 아예 똑같은 코드를 쳐봐도 시간초과라고 나옵니다.
아래에 첨부한 코드는 초반에 제가 입력한 코드인데, 어느 부분에서 시간초과가 나는 건지 알려주실 수 있을까요?

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

public class Code27 {
    public static int n, m;
    public static int min = Integer.MAX_VALUE;
    public static ArrayList<Dis> house, pizza;
    public static Dis[] selected;

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        house = new ArrayList<>();
        pizza = new ArrayList<>();
        selected = new Dis[m];

        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                int location = sc.nextInt();
                if(location==1) house.add(new Dis(i, j));
                else if(location==2) pizza.add(new Dis(i, j));
            }
        }
        DFS(0,0);
        System.out.println(min);
    }

    public static void DFS(int L, int start){
        if(L==m){
            min = Math.min(min, distCalc(selected));
        }else{
            for(int i=start; i<pizza.size(); i++){
                selected[L] = pizza.get(i);
                DFS(L+1, start+1);
            }
        }
    }

    public static int distCalc(Dis[] selected){
        int sum = 0;
        for(Dis h : house){
            int dis = Integer.MAX_VALUE;
            for(int j=0; j<selected.length; j++){
                dis = Math.min(dis,(Math.abs(h.x - selected[j].x) + Math.abs(h.y - selected[j].y)));
            }
            sum += dis;
        }
        return sum;
    }
}
코테 준비 같이 해요! java

Answer 2

0

DFS(L+1, start+1)

이부분이 정답과 다른 것 같아요!

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

제가 봐도 selected 를 객체 배열로 잡은 것 이외에는 딱히 시간초과가 날 사항이 없어 보입니다. 제가 제공한 정답코드로 채점해보세요. 저는 방금 제 코드로 해보니 정상처리가 됩니다. 제공한 코드와 본인 코드를 비교해보세요.

lsh81552606's profile image
lsh81552606

asked

Ask a question