问题:n个ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] graph = new int[n][n];
for (int[] flight : flights) {
graph[flight[0]][flight[1]] = flight[2];
}
boolean[] visited = new boolean[n];
int[] minCost = {Integer.MAX_VALUE};
findCheapestPrice(graph, visited, src, dst, K, minCost, 0);
return minCost[0] == Integer.MAX_VALUE ? -1 : minCost[0];
}
private void findCheapestPrice(int[][] graph, boolean[] visited,
int src, int dst, int K, int[] minCost, int cost) {
if (src == dst) {
minCost[0] = Math.min(minCost[0], cost);
}
if (K >= 0 && cost < minCost[0]) {
for (int i = 0; i < graph.length; ++i) {
if (graph[src][i] != 0 && !visited[i]) {
visited[i] = true;
findCheapestPrice(graph, visited, i, dst, K - 1,
minCost, cost + graph[src][i]);
visited[i] = false;
}
}
}
}
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
基于广度优先搜索算法的参考代码如下:
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] graph = new int[n][n];
for (int[] flight : flights) {
graph[flight[0]][flight[1]] = flight[2];
}
int[] costs = new int[n];
Arrays.fill(costs, Integer.MAX_VALUE);
Set<Integer> set1 = new HashSet<>();
set1.add(src);
costs[src] = 0;
while (!set1.isEmpty() && K >= 0) {
Set<Integer> set2 = new HashSet<>();
for (int from : set1) {
for (int i = 0; i < n; ++i) {
if (graph[from][i] > 0 && costs[from] + graph[from][i] < costs[i]) {
costs[i] = costs[from] + graph[from][i];
set2.add(i);
}
}
}
set1 = set2;
K--;
}
return costs[dst] == Integer.MAX_VALUE ? -1 : costs[dst];
}
上述代码中数组costs的意义是经过若干步骤之后从src出发到达每个城市的最低票价。
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] dp = new int[2][n];
for (int[] row : dp) {
Arrays.fill(row, Integer.MAX_VALUE);
}
dp[0][src] = 0;
int cur = 1;
while (K >= 0) {
int prev = 1 - cur;
for (int[] flight : flights) {
if (dp[prev][flight[0]] < Integer.MAX_VALUE) {
dp[cur][flight[1]] = Math.min(dp[cur][flight[1]],
dp[prev][flight[0]] + flight[2]);
}
}
dp[prev] = Arrays.copyOf(dp[cur], n);
cur = prev;
K--;
}
return dp[1 - cur][dst] == Integer.MAX_VALUE ? -1 : dp[1 - cur][dst];
}
ortant; word-wrap: break-word !imp
ortant; word-wrap: break-word !imp