[Leetcode] Cheapest Flights Within K Stops K次转机最便宜机票

最新更新请见:https://yanjia.me/zh/2019/01/…

There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.

Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

广度优先搜索

思路

本题给定起始点和重点,还给定各个点之间的连接,一看就知道是要搜索。另外由于给定了最大深度K,使用广度优先搜索会比较方便,因为每一层的深度都是一样的,不用像DFS那样来回修改深度值。这题OJ的难点在于如何剪枝来满足对时间和空间的优化,对于某一个航线,在什么样的情况下可以确认不用再往下寻找了呢?自然地想到用一个visited的map来记录哪些访问过,可是即使访问过,也不能完全说明不用继续寻找了,因为可能某种方案虽然中转多后面才遇到,但是总价却少。所以对于每个访问过的节点,我们要记录当前最低的总价,只有当到达该地新的总价更低时,才继续寻找,如果该方案到达该地的总价已经高于之前的方案的话,就没有必要继续寻找了,从该地到终点的最优线路反正都是一样的。

代码

Go

func buildGraph(flights [][]int) map[int]map[int]int {
    graph := map[int]map[int]int{}
    for _, flight := range flights {
        src, dst, cost := flight[0], flight[1], flight[2]
        cmap, ok := graph[src]
        if !ok {
            cmap = map[int]int{}
        }
        // cmap is a map from destination to cost
        cmap[dst] = cost
        graph[src] = cmap
    }
    return graph
}

func findCheapestPrice(n int, flights [][]int, src int, dst int, K int) int {
    // build the graph given edges first
    graph := buildGraph(flights)
    queue := [][]int{{src, 0}}
    stops := -1
    cheapest := math.MaxInt64
    visited := map[int]int{}
    // BFS
    for len(queue) > 0 && stops <= K {
        size := len(queue)
        for i := 0; i < size; i++ {
            curr := queue[i]
            from, sum := curr[0], curr[1]
            if from == dst && sum < cheapest {
                cheapest = sum
                continue
            }
            toMap := graph[from]
            for to, cost := range toMap {
                // if the total cost is higher than before, there's no need to keep looking
                if min, ok := visited[to]; ok && sum+cost > min {
                    continue
                }
                queue = append(queue, []int{to, sum + cost})
                visited[to] = sum + cost
            }
        }
        queue = queue[size:len(queue)]
        stops++
    }
    if cheapest == math.MaxInt64 {
        return -1
    }
    return cheapest
}
    原文作者:ethannnli
    原文地址: https://segmentfault.com/a/1190000018010313
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞