Leetcode 787. K 站中转内最便宜的航班
DFS:
class Solution { int MAX=99999999; int[][] G=new int[100][100]; int[] d=new int[100]; int[] path=new int[100]; boolean visit[]=new boolean[100]; int N=0; int res=MAX; int times=0; public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { for (int i=0;i<100;i++){ for (int j=0;j<100;j++){ G[i][j]=MAX; } } N=n; times=K; for (int[] flight: flights) { G[flight[0]][flight[1]]=flight[2]; } DFS(src,dst,0,0); return res==MAX?-1:res; // return Integer.MAX_VALUE; } public void DFS(int now,int dst,int cost,int k){ if(k-1>times)return; if(now==dst){ res=cost; return; } for (int i=0;i<N;i++){ if(visit[i]==false&&cost+G[now][i]<res){ visit[i]=true; DFS(i,dst,cost+G[now][i],k+1); visit[i]=false; } } } }
BFS: