815. Bus Routes

https://leetcode.com/problems/bus-routes/description/?envType=company&envId=tiktok&favoriteSlug=tiktok-three-months

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        to_route=defaultdict(set)
        for i,r in enumerate(routes):
            for j in r:
                to_route[j].add(i)
        
        bfs=[(source,0)]
        seen=set([source])

        for stop,dist in bfs:
            if stop==target:return dist
            for i in to_route[stop]:
                for j in routes[i]:
                    if j not in seen:
                        bfs.append((j,dist+1))
                        seen.add(j)
                routes[i]=[]
        return -1

 if stop==target:return dist 这一行要在开始

routes[i]=[]这个剪枝很有必要

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码是一个求解公交路线最短路径的算法,需要用到图论中的 Floyd 算法,可以按照以下方式完善代码: ``` #include <iostream> #include <vector> #include <map> #include <climits> using namespace std; int findShortestPath(int source, int target, vector<vector<int>>& routes) { map<int, vector<int>> m; for (int i = 0; i < routes.size(); i++) { for (auto &j : routes[i]) { m[j].emplace_back(i); } } vector<vector<int>> path(routes.size(), vector<int>(routes.size(), INT_MAX)); // 创建 N * N 的矩阵 for (auto &kv : m) { for (auto &bus : kv.second) { for (auto &bus1 : kv.second) { path[bus][bus1] = (bus1 != bus) ? 1 : 0; } } } for (int k = 0; k < routes.size(); k++) { for (int i = 0; i < routes.size(); i++) { for (int j = 0; j < routes.size(); j++) { if (path[i][k] == INT_MAX || path[k][j] == INT_MAX) continue; if (path[i][j] > path[i][k] + path[k][j]) { path[i][j] = path[i][k] + path[k][j]; } } } } int res = INT_MAX; for (auto bus1 : m[source]) { for (auto bus2 : m[target]) { res = min(res, path[bus1][bus2]); // 找出 source 和 target 对应的任意一组公交车之间的最短路径长度 } } return res == INT_MAX ? -1 : (source == target) ? res : res + 1; } int main() { vector<vector<int>> routes = {{1, 2, 7}, {3, 6, 7}}; int source = 1; int target = 6; int res = findShortestPath(source, target, routes); cout << res << endl; return 0; } ``` 在这个示例代码中,我们假设有两条公交路线,第一条为 1-2-7,第二条为 3-6-7,要求求解从点 1 到点 6 的最短路径。因此,输入参数为 source=1, target=6, routes={{1, 2, 7}, {3, 6, 7}}。运行结果为 2,即从点 1 到点 6 的最短路径长度为 2。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值