https://www.acmicpc.net/problem/14889
문제 유형
- 브루트 포스
- 백트래킹
풀이
public class boj14889 {
static int n;
static int [][] board;
static boolean [] visited;
static int res = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
board = new int[n][n];
visited = new boolean[n];
for(int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j < n; j++) {
board[i][j] = Integer.parseInt(st.nextToken());
}
}
dfs(0, 0);
System.out.println(res);
}
public static void dfs(int idx, int cnt) {
if (cnt == n/2) {
int start = 0;
int link = 0;
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
if (visited[i] && visited[j]) {
start += board[i][j] + board[j][i];
}
if (!visited[i] && !visited[j]) {
link += board[i][j] + board[j][i];
}
}
}
res = Math.min(res, Math.abs(link - start));
return;
}
for(int i = idx; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
dfs(i, cnt + 1);
visited[i] = false;
}
}
}
}
회고
'Algorithm > 백준' 카테고리의 다른 글
[백준] Silver I. 회전 초밥 (1) | 2024.10.21 |
---|---|
[백준] Gold V. 강의실 배정 (0) | 2024.10.12 |
[백준] Gold IV. 즐거운 단어 (0) | 2024.09.26 |
[백준] Silver II. 꽃길 (0) | 2024.09.26 |
[백준] Gold IV. 케이크 자르기 (0) | 2024.09.05 |