https://www.acmicpc.net/problem/15686
15686번: 치킨 배달
크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸
www.acmicpc.net
[문제]
[풀이]
치킨 집 - 가정 집 사이의 거리를 최소로 하는 치킨 집들을 구해서 거리 합을 구하는 문제이다.
주어진 map 상태를 보면 중간에 벽이 없이 거리는 (x2-x1)+(y2-y1) 으로 구하면 되기 때문에
그래프를 탐색 하지 않고 모든 치킨 집과 가정 집 사이의 거리를 다 구해서
최소를 찾는 완전탐색을 하면 된다.
탐색의 크기는 치킨 집 좌표의 갯수를 기준으로 visit 방문 배열의 크기로 정해준다.
import java.util.stream.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.*;
import java.util.*;
import java.io.*;
public class Main {
static boolean[] visit;
static ArrayList<int[]> house,chicken;
static int[][] map;
static int n,m,minSum=Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] input = stream(br.readLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
n = input[0]; m = input[1];
map = new int[n][n];
house = new ArrayList<>();
chicken = new ArrayList<>();
for(int i=0;i<n;i++){
map[i] = stream(br.readLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
for(int j=0;j<n;j++){
if(map[i][j]==1) house.add(new int[]{j,i});
else if(map[i][j]==2) chicken.add(new int[]{j,i});
}
}//end input
visit = new boolean[chicken.size()];// 치킨 집 갯수만큼 크기 지정
dfs(0,0,new ArrayList<Integer>());
System.out.println(minSum);
}
static void dfs(int cur, int depth, ArrayList<Integer> indexList) {
if(depth==m){
int distanceSum=0;
for (int[] housePos : house) {
int minDistance=Integer.MAX_VALUE;
for (Integer index : indexList) {
int[] chickenPos = chicken.get(index);
minDistance = Math.min(Math.abs(chickenPos[1] - housePos[1])+
Math.abs(chickenPos[0] - housePos[0]),minDistance);
}
distanceSum+=minDistance;
}
minSum = Math.min(distanceSum,minSum);
return;
}
for(int next=cur;next<chicken.size();next++){
if(!visit[next]){
visit[next]=true;
indexList.add(next); // 치킨 집 인덱스 추가
dfs(next,depth+1,indexList);
visit[next]=false;
indexList.remove((Integer)next); // object 형태로 형 변환해서 제거
}
}
}
}
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1865] 웜홀 JAVA (0) | 2022.04.04 |
---|---|
[BOJ] 백준 [1043] 거짓말 JAVA (0) | 2022.04.02 |
[BOJ] 백준 [16234] 인구이동 JAVA (0) | 2022.03.10 |
[BOJ] 백준 [14442] 벽 부수고 이동하기 2JAVA (0) | 2022.03.09 |
[BOJ] 백준 [3109] 빵집 JAVA (0) | 2022.03.07 |