You are on page 1of 2

Bài tập tuần 3

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

static int n, costs[][] = new int[105][105], x[] = new int[100];


static boolean visited[] = new boolean[105];
static int minCost = Integer.MAX_VALUE;
static int currentCost;

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
costs[i][j] = sc.nextInt();
}
}
Arrays.fill(visited, false);
x[1] = 1;
visited[1] = true;

findMinCost(2);
System.out.println(minCost);
sc.close();
}
static void findMinCost(int i) {
if (i == n + 1) {
currentCost = costs[x[n]][x[1]];
for (int j = 1; j < n; j++) {
currentCost += costs[x[j]][x[j + 1]];
}
minCost = Math.min(minCost, currentCost);
return;
}
for (int j = 1; j <= n; j++) {
if (!visited[j]) {
visited[j] = true;
x[i] = j;
currentCost = costs[x[i - 1]][x[i]];
findMinCost(i + 1);

visited[j] = false;
}
}
}
}

You might also like