问题描述
这个问题来自 leetcode 竞赛。 https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/
一些测试用例失败了。
有一个国家有 n 个城市,编号从 0 到 n - 1,其中所有城市都通过双向道路相连。道路表示为边的二维整数数组,其中边 [i] = [xi,yi,timei] 表示城市 xi 和 yi 之间的道路需要时间分钟才能行驶。连接同一两个城市的可能有多条不同旅行时间的道路,但没有道路将城市与其自身相连。
每次经过一个城市,都必须支付通行费。这表示为长度为 n 的 0 索引整数数组,其中 passingFees[j] 是您通过城市 j 时必须支付的美元金额。
一开始,您在城市 0 并希望在 maxTime 分钟或更短的时间内到达城市 n - 1。您的旅程费用是您在旅程的某个时刻(包括源城市和目的地城市)经过的每个城市的通行费总和。
给定 maxTime、edges 和 passingFees,返回完成旅程的最低成本,如果您无法在 maxTime 分钟内完成,则返回 -1。
Input: maxTime = 30,edges = [[0,1,10],[1,2,[2,5,[0,3,1],[3,4,[4,15]],passingFees = [5,20,3]
Output: 11
Explanation: The path to take is 0 -> 1 -> 2 -> 5,which takes 30 minutes and has $11 worth of passing
fees.
class Solution {
public class pair{
int v;
int time;
public pair(int v,int time){
this.v=v;
this.time=time;
}
}
public int minCost(int maxTime,int[][] edges,int[] passingFees) {
HashMap<Integer,ArrayList<pair>> map=new HashMap<>();
int n=passingFees.length;
for(int i=0;i<n;i++) map.put(i,new ArrayList<pair>());
// adding all adjacent vertices
for(int[] edge:edges){
int x=edge[0];
int y=edge[1];
map.get(x).add(new pair(y,edge[2]));
map.get(y).add(new pair(x,edge[2]));
}
int[] cost=new int[n]; //Costs from node v to n-1
boolean[] stack=new boolean[n];// if the current node is in recusion stack to avoid cycles
Arrays.fill(stack,false);
Arrays.fill(cost,-1);
dfs(maxTime,map,passingFees,cost,stack,0);
if(cost[n-1]==-1) return -1;
return cost[0];
}
public int dfs(int maxTime,HashMap<Integer,ArrayList<pair>> map,int[] passingFees,int[] cost,boolean[] stack,int index,int time){
//System.out.println(index+" "+time);
if(time>maxTime) return 1000000;
if(stack[index]) return 1000000;
if(cost[index]!=-1) return cost[index];
int currCost=passingFees[index];// current node's cost
if(index==passingFees.length-1){
cost[index]=currCost;
return currCost;
}
stack[index]=true; // adding current node to the recursion
int minCost=1000000;
for(pair p:map.get(index)){
int costP=dfs(maxTime,p.v,time+p.time); // checking cost from each adjacent node to destination
//System.out.println("index and cost "+index+" "+cost);
minCost=Math.min(minCost,costP); //taking the minimum of the costs from adjacent node
}
stack[index]=false;// removing current node from recursion
cost[index]=currCost+minCost;//total cost
return cost[index];
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)