[Leetcode] 815. Bus route Routes

Source: Internet
Author: User

We have a list of bus routes. Each are routes[i] a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7] , this means then the First Bus (0-th indexed) travels in the sequence 1->5->7->1->5->7 ->1-> forever.

We start at bus stop S (initially not on a bus), and we want to go bus stop T . Travelling by buses only, what's the least number of buses we must take to reach our destination? Return-1 if it is not possible.

Example:Input:routes = [[1, 2, 7], [3, 6, 7]]s = 1T = 6output:2explanation:the Best strategy are take-the first bus to T He bus stop 7, then take the second bus to the bus stop 6.

Note:

    • 1 <= routes.length <= 500.
    • 1 <= routes[i].length <= 500.
    • 0 <= routes[i][j] < 10 ^ 6.

There is a two-dimensional array that represents the bus route, each element Routes[i] represents the circular route of each bus cycle, and the minimum number of buses required to get from the bus stop s to T.

Solution: BFS, first to the original two-dimensional array processing, the two-dimensional array of each row represents the bus can reach the site, with HashMap record a site has a bus pass. After this processing, we know that each site has a bus passed. Then with a queue record the current site, for the current site of all the transit cycle, each bus has its own next site. Can be imagined as a figure, each bus site by how many bus pass, that is to say, is a transit point, can be connected to another bus, because the problem is to go through the number of public transport and do not care about the number of bus sites, so in the BFS when the bus (that is, routes subscript) to expand.

Java:

Class Solution {public int numbusestodestination (int[][] routes, int S, int T) {hashset<integer> visited       = new Hashset<> ();       queue<integer> q = new linkedlist<> ();       Hashmap<integer, arraylist<integer>> map = new hashmap<> ();                int ret = 0;                if (s==t) return 0; for (int i = 0, i < routes.length; i++) {for (int j = 0; J < Routes[i].length; J + +) {Arrayli                St<integer> buses = Map.getordefault (Routes[i][j], New arraylist<> ());                Buses.add (i);                            Map.put (Routes[i][j], buses);        }} q.offer (S);           while (!q.isempty ()) {int len = q.size ();           ret++;               for (int i = 0; i < len; i++) {int cur = q.poll ();               Arraylist<integer> buses = map.get (cur); for (int bus:buses) {if (visited.Contains (bus)) continue;                    Visited.add (bus);                        for (int j = 0; J < Routes[bus].length; J + +) {if (routes[bus][j] = = T) return ret;                     Q.offer (Routes[bus][j]);    }}}} return-1;   }}

Java:

public int numbusestodestination (int[][] routes, int S, int T) {hashmap<integer, hashset<integer>> to_        Routes = new hashmap<> (); for (int i = 0; i < Routes.length, ++i) for (int j:routes[i]) {if (!to_routes.containskey (                j)) To_routes.put (J, New Hashset<integer> ());            To_routes.get (j). Add (i);        } queue<point> BFS = new Arraydeque ();        Bfs.offer (new Point (S, 0));        Hashset<integer> seen = new hashset<> ();        Seen.add (S);            while (!bfs.isempty ()) {int stop = Bfs.peek (). x, bus = Bfs.peek (). Y;            Bfs.poll ();            if (stop = = T) return bus; For (Int. route_i:to_routes.get (STOP)) for (int next_stop:routes[route_i]) if (!seen.                        Contains (Next_stop)) {Seen.add (next_stop);                    Bfs.offer (new Point (next_stop, bus + 1));    }        }    return-1; }

Python:

def numbusestodestination (self, routes, S, T):        to_routes = collections.defaultdict (set) for        I,route in Enumerate (routes):            for J in Route:to_routes[j].add (i)        BFS = [(s,0)]        seen = set ([S])        for stop, bus in BFS:            if stop = = T:return bus for            route_i in To_routes[stop]: for                next_stop in routes[route_i]:                    if Next_stop n OT in seen:                        bfs.append ((Next_stop, bus+1))                        Seen.add (next_stop)                routes[route_i] = []        return-1

Python:

# Time:o (| v| + | e|) # Space:o (| v| + | e|) Import Collectionsclass Solution (object): Def numbusestodestination (self, routes, S, T): "" ": Type routes : List[list[int]]: type S:int:type t:int:rtype:int "" "If S = = T:retur                 N 0 to_route = collections.defaultdict (set) for I, Route in enumerate (routes): For stop in Route:            To_route[stop].add (i) result = 1 Q = [s] lookup = set ([s]) while Q: Next_q = [] for stop in q:for I in To_route[stop]: for Next_stop in routes[  I]: if next_stop in Lookup:continue if Next_stop = = T:return result Next_q.append (next_stop) to_           Route[next_stop].remove (i) lookup.add (next_stop) q = next_q Result + = 1 return-1   

C++:

int Numbusestodestination (vector<vector<int>>& routes, int S, int T) {        unordered_map<int, Unordered_set<int>> To_route;        for (int i = 0; i < routes.size (), ++i) for (auto& J:routes[i]) To_route[j].insert (i);        Queue<pair<int, int>> BFS; Bfs.push (Make_pair (S, 0));        Unordered_set<int> seen = {S};        while (!bfs.empty ()) {            int stop = Bfs.front (). First, bus = Bfs.front (). Second;            Bfs.pop ();            if (stop = = T) return bus;            For (auto& Route_i:to_route[stop]) {for                (auto& next_stop:routes[route_i])                    if (Seen.find (next_stop) = = Seen.end ()) {                        Seen.insert (next_stop);                        Bfs.push (Make_pair (next_stop, bus + 1));                    }                Routes[route_i].clear ();            }        }        return-1;    }

  

[Leetcode] 815. Bus route Routes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.