제목
제출 코드
- 사용 알고리즘 :
백트래킹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package jungol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class J1681_hamiltonianCycle {
static int N, result = Integer.MAX_VALUE;
static int[][] arr;
static boolean[] visit;
static void go(int n, int from, int sum) {
if(result <= sum) return;
if(n==N-1) {
if(arr[from][0]!=0) result = Math.min(result, sum+arr[from][0]);
return;
}
for(int i=0; i<N; i++) {
if(!visit[i] && arr[from][i]!=0) {
visit[i] = true;
go(n+1, i, sum+arr[from][i]);
visit[i] = false;
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
visit = new boolean[N];
for(int i=0; i<N; i++) {
String[] line = br.readLine().split(" ");
for(int j=0; j<N; j++) {
arr[i][j] = Integer.parseInt(line[j]);
}
}
visit[0] = true;
go(0, 0, 0);
System.out.println(result);
}
}