
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static class Pos {
private int y;
private int x;
Pos(int y, int x) {
this.y = y;
this.x = x;
}
}
static BufferedReader br;
static BufferedWriter bw;
static int N;
static int M;
static int[][] board;
static List<Pos> homeList;
static List<Pos> chickenList;
public static List<List<Pos>> selectChickens() {
List<List<Pos>> result = new ArrayList<>();
List<Pos> selected = new ArrayList<>();
backtracking(0, selected, result);
return result;
}
public static void backtracking(int start, List<Pos> selected, List<List<Pos>> result) {
if (selected.size() >= 1 && selected.size() <= M) {
result.add(new ArrayList<>(selected));
}
if (selected.size() == M) {
return;
}
for (int i = start; i < chickenList.size(); i++) {
selected.add(chickenList.get(i));
backtracking(i + 1, selected, result);
selected.remove(selected.size() - 1);
}
}
public static int getChickenDistance(List<Pos> selectChickens) {
int sum = 0;
for (Pos homePos : homeList) {
int minDistance = Integer.MAX_VALUE;
for (Pos chickenPos : selectChickens) {
int calc = Math.abs(chickenPos.y - homePos.y) + Math.abs(chickenPos.x - homePos.x);
minDistance = Math.min(minDistance, calc);
}
sum += minDistance;
}
return sum;
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
homeList = new ArrayList<>();
chickenList = new ArrayList<>();
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
board = new int[N + 1][N + 1];
for (int y = 1; y <= N; y++) {
st = new StringTokenizer(br.readLine());
for (int x = 1; x <= N; x++) {
board[y][x] = Integer.parseInt(st.nextToken());
if (board[y][x] == 1) {
homeList.add(new Pos(y, x));
} else if (board[y][x] == 2) {
chickenList.add(new Pos(y, x));
}
}
}
br.close();
int minDistance = Integer.MAX_VALUE;
for (List<Pos> selectedChickedList : selectChickens()) {
int calc = getChickenDistance(selectedChickedList);
minDistance = Math.min(minDistance, calc);
}
bw.write(minDistance + "\n");
bw.close();
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 1043번: 거짓말 (0) | 2025.04.30 |
|---|---|
| [JAVA-자바] 17070번: 파이프 옮기기 1 (0) | 2025.04.29 |
| [JAVA-자바] 11003번: 최솟값 찾기 (0) | 2025.04.24 |
| [JAVA-자바] 13549번: 숨바꼭질 3 (0) | 2025.04.23 |
| [JAVA-자바] 12865번: 평범한 배낭 (0) | 2025.04.23 |