package work;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Airfare {
static int T, N, mincost;
static int data[][];
static boolean used[];
public static void main(String[] args) throws FileNotFoundException {
/* Scanner sc=new Scanner(System.in); */
Scanner sc = new Scanner(new File("src/airfare"));
T = sc.nextInt();
for (int t = 0; t < T; t++) {
N = sc.nextInt();
data = new int[N + 1][N + 1];
used = new boolean[N + 1];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
data[i][j] = sc.nextInt();
}
}
mincost = 0xfffffff;
used[1] = true;
if (N == 1) {
mincost = data[1][1];
} else {
dfs(1, 0);
}
System.out.println(mincost);
}
}
private static void dfs(int step, int sum) {
if (check()) {
if (data[step][1] != 0 && mincost > sum + data[step][1])
mincost = sum + data[step][1];
return;
}
//
if (sum > mincost)
return;
//
for (int i = 1; i <= N; i++) {
if (!used[i]) {
if (data[step][i] != 0) {
used[i] = true;
dfs(i, sum + data[step][i]);
used[i] = false;
}
}
}
}
private static boolean check() {
for (int i = 1; i <= N; i++) {
if (used[i] == false)
return false;
}
return true;
}
}
、、input
2
5
0 14 4 10 20
14 0 7 8 7
4 5 0 7 16
11 7 9 0 2
18 7 17 4 0
5
9 9 2 9 5
6 3 5 1 5
1 8 3 3 3
6 0 9 6 8
6 6 9 4 8
、、output
30
18