백준 2098 외판원순회
유형
코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TSP {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer stz;
static int N;
static int[][] dist;
static int[][] dp;
static int INF = 20000000;
public static void main(String[] args) throws Exception {
N = Integer.parseInt(br.readLine());
dist = new int[N][N];
dp = new int[N][1 << N];
for(int i = 0; i < N; i++) {
Arrays.fill(dp[i], INF);
}
for(int i = 0; i < N; i++) {
stz = new StringTokenizer(br.readLine());
for(int j = 0; j < N; j++) {
dist[i][j] = Integer.parseInt(stz.nextToken());
}
}
System.out.println(tsp(0, 1));
}
public static int tsp(int current, int visited) {
if((visited == (1 << N) - 1)) {
if (dist[current][0] == 0) return INF;
return dist[current][0];
}
if (dp[current][visited] != INF) {
return dp[current][visited];
}
for (int k = 0; k < N; k++) {
int next = 1 << k;
if (dist[current][k] == 0 || (visited & next) != 0) {
continue;
}
dp[current][visited] = Math.min(dp[current][visited], tsp(k, visited | next) + dist[current][k]);
}
return dp[current][visited];
}
}