LC815. Bus Routes

2018/04/15 Leetcode

原题链接:[LC815] (https://leetcode.com/problems/bus-routes/description/)

题目概述: 输入是若干行公交线,每个数代表一站bus stop, [[1, 2, 7]], [3, 6, 7]], 在给定某站S位起点,问最少需要多少趟公交到达T站。比如始发是S=2站,经过2辆公交车能到达T=6,没有返回-1

题目思路:
1) 维护一个queue,里面存放待判定的站点, 每一层while循环都会增加一趟公交车
2) 遍历所有队列内站点,对每个站点,取出经过该点的所有线路.
3)遍历所有没被visited过的线路,并标记该线路为visited

  • 如果站点等于终点,则return
  • 反之则加入队列,等待下一轮的遍历
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
    unordered_map<int, vector<int>> m;  // bus_stop, bus_line
    queue<int> q;
    unordered_set<int> visited;
    int res = 0;
    // 记录每站路过的公交车代号
    for(int i = 0; i < routes.size(); i++) 
        for(auto stop : routes[i]) 
            m.count(stop) ? m[stop].push_back(i): m[stop] = {i};
    
    if (S==T && m.count(S)) return 0; // for 
    
    q.push(S);
    while(!q.empty()) {
        res++;
        int len = q.size();
        // 遍历本层所有队列的站点
        for(int i = 0; i < len; i++) {
            int stop = q.front(); q.pop();
            for(auto line_id: m[stop]) {                  
                if (visited.count(line_id)) continue;
                visited.insert(line_id);
                for(auto bus_stop : routes[line_id]) {
                     if (bus_stop == T) return res;
                     q.push(bus_stop);
                }
            }
        }
    }
    return -1;
}

Search

    Table of Contents