import java.util.HashMap;
public class SingleS {
static int adjMatrix[][];
static HashMap<int[], Integer> mp
= new HashMap<int[], Integer>();
static int DFSUtility(int node, int stops, int dst,
int cities)
{
if (node == dst)
return 0;
if (stops < 0)
return Integer.MAX_VALUE;
int[] key = new int[] { node, stops };
if (mp.containsKey(key))
return mp.get(mp);
int ans = Integer.MAX_VALUE;
for (int neighbour = 0; neighbour < cities;
++neighbour) {
int weight = adjMatrix[node][neighbour];
if (weight > 0) {
int minVal = DFSUtility(
neighbour, stops - 1, dst, cities);
if (minVal + weight > 0)
ans = Math.min(ans, minVal + weight);
}
mp.put(key, ans);
}
return ans;
}
static int findCheapestPrice(int cities,
int[][] flights, int src,
int dst, int stops)
{
adjMatrix = new int[cities + 1][cities + 1];
for (int[] item : flights) {
adjMatrix[item[0]][item[1]] = item[2];
}
int ans = DFSUtility(src, stops, dst, cities);
return ans >= Integer.MAX_VALUE ? -1 : ans;
}
public static void main(String[] args)
{
int[][] flights
= { { 4, 1, 1 }, { 1, 2, 3 }, { 0, 3, 2 },
{ 0, 4, 10 }, { 3, 1, 1 }, { 1, 4, 3 } };
int stops = 2;
int totalCities = 5;
int sourceCity = 0;
int destCity = 4;
int ans = findCheapestPrice(totalCities, flights,
sourceCity, destCity,
stops);
System.out.println(ans);
}
}