字节跳动2019春招试题五——旅行
题目来自牛客网,感谢!
给定各地之间交通的经费矩阵,计算从某一地出发经过其他所用地点并最后回到出发地的总经费的最小值
输入格式:
第一行输入地点数N
第二至N+1行每行输入N个数据,构成经费矩阵MN×N
输入保证 1 < N ≤ 20 1<N \leq 20 1<N≤20
输出格式:
第一行输出所需最小经费
输入范例:
4
0 2 6 5
2 0 4 4
6 4 0 2
5 4 2 0
输出范例:
13
这道题一开始实际上没什么思路,画了好几个矩阵,研究矩阵中点的意义和连线的意义等等。后来放弃了用(大概是) 深度优先搜索的算法去解了。算法很朴素,也没有优化,可想而知地超时了……
我的代码实现:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
//无向有权完全图的最优遍历环
public class Journey {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] cost = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cost[i][j] = sc.nextInt();
sc.nextLine();
}
sc.close();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
map.put(i, 1);
System.out.println(DFS(map, cost, 0, 0));
}
public static int DFS(Map<Integer, Integer> map, int[][] cost, int source, int target) {
int size = 0;
for (Integer k : map.keySet())
if (map.get(k) == 1)
size++;
if (size == 1)
return cost[source][target];
int s = 0;
for (Integer k : map.keySet()) {
if (k.equals(target) || map.get(k) == 0)
continue;
map.put(k, 0);
int ss = cost[source][k] + DFS(map, cost, k, target);
if (s == 0)
s = ss;
else
s = Math.min(s, ss);
map.put(k, 1);
}
return s;
}
}