• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

피자배달거리

21.05.06 21:40 작성 조회수 102

0

해당 코드가 왜 타임 아웃이 되는지 모르겠습니다.

강사님의 코드를 베꼈는데도 왜 그런지 모르겠습니다.

import java.util.ArrayList;
import java.util.Scanner;


class Point {
int x;
int y;

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

public class Main {
static int n, m, len, answer = Integer.MAX_VALUE;
static int[] combi;
static ArrayList<Point> pz, hs;

public void DFS(int L, int s){
if (L == m){
// 모든 피자 가게 중에서 m개를 뽑는 모든 경우
// 최소 피자 배달거리 구하기
int sum = 0;
for (Point h : hs) {
int dis = Integer.MAX_VALUE;
for (int i : combi){
dis = Math.min(dis, Math.abs(h.x - pz.get(i).x) + Math.abs(h.y - pz.get(i).y));
}
sum += dis;
}
answer = Math.min(answer, sum);
}
else {
for (int i = s; i < len; i++) {
combi[L] = i;
DFS(L + 1, s + 1);
}
}
}


public static void main(String[] args){
Main T = new Main();
Scanner kb=new Scanner(System.in);
n = kb.nextInt();
m = kb.nextInt();

pz = new ArrayList<>();
hs = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int tmp = kb.nextInt();
if (tmp == 1)
hs.add(new Point(i, j));
else if (tmp == 2)
pz.add(new Point(i, j));
}
}
len = pz.size();
combi = new int[m];
T.DFS(0, 0);
System.out.println(answer);
return ;
}
}

답변 1

답변을 작성해보세요.

1

안녕하세요^^

조합을 잘못 돌리고 있는 코드입니다.

DFS(L + 1, s + 1);

s+1 이 아니라 i+1 입니다.

채널톡 아이콘