字节跳动2019春招试题五——旅行

字节跳动2019春招试题五——旅行

题目来自牛客网,感谢!

给定各地之间交通的经费矩阵,计算从某一地出发经过其他所用地点并最后回到出发地的总经费的最小值

输入格式:

第一行输入地点数N
第二至N+1行每行输入N个数据,构成经费矩阵MN×N
输入保证 1 < N ≤ 20 1<N \leq 20 1<N20

输出格式:

第一行输出所需最小经费

输入范例:

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值