<p>You are given an array <code>routes</code> representing bus routes where <code>routes[i]</code> is a bus route that the <code>i<sup>th</sup></code> bus repeats forever.</p>

<ul>
	<li>For example, if <code>routes[0] = [1, 5, 7]</code>, this means that the <code>0<sup>th</sup></code> bus travels in the sequence <code>1 -&gt; 5 -&gt; 7 -&gt; 1 -&gt; 5 -&gt; 7 -&gt; 1 -&gt; ...</code> forever.</li>
</ul>

<p>You will start at the bus stop <code>source</code> (You are not on any bus initially), and you want to go to the bus stop <code>target</code>. You can travel between bus stops by buses only.</p>

<p>Return <em>the least number of buses you must take to travel from </em><code>source</code><em> to </em><code>target</code>. Return <code>-1</code> if it is not possible.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> routes = [[1,2,7],[3,6,7]], source = 1, target = 6
<strong>Output:</strong> 2
<strong>Explanation:</strong> The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
<strong>Output:</strong> -1
</pre>

<p>&nbsp;</p>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= routes.length &lt;= 500</code>.</li>
	<li><code>1 &lt;= routes[i].length &lt;= 10<sup>5</sup></code></li>
	<li>All the values of <code>routes[i]</code> are <strong>unique</strong>.</li>
	<li><code>sum(routes[i].length) &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= routes[i][j] &lt; 10<sup>6</sup></code></li>
	<li><code>0 &lt;= source, target &lt; 10<sup>6</sup></code></li>
</ul>

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        # bfs, two nodes connected iff they have shared stations
        # station_to_routes => use hash set to help build graph, station to route indexes
        # graph[i] => routes that the ith route connects to 
        # node is route
        if source == target: return 0
        n = len(routes)
        station_to_routes = defaultdict(set)
        target_routes = set()
        for idx, route in enumerate(routes):
            for station in route:
                station_to_routes[station].add(idx)
                if station == target: 
                    target_routes.add(idx)
        """
        graph = [set() for _ in range(n)]
        for idx, route in enumerate(routes):
            for station in route:
                for neighbor_route in station_to_routes[station]:
                    if neighbor_route != idx: 
                        graph[idx].add(neighbor_route)

        queue = deque(list(station_to_routes[source]))
        visited = [False for _ in range(n)]
        for route in queue: visited[route] = True
        step = 1
        while queue:
            queue_len = len(queue)
            for i in range(queue_len):
                curr_route = queue.popleft()
                if curr_route in target_routes: return step
                for neighbor in graph[curr_route]:
                    if not visited[neighbor]:
                        visited[neighbor] = True
                        queue.append(neighbor)
            step += 1
        return -1
        """
        # optimization, node is station and use two visited sets in BFS so that dont need to build graph
        # seems the above graph took much time to build (though its still an acceptable solution)
        routes_to_stations = [set(x) for x in routes]
        queue = deque([source])
        visited_routes = set()
        visited_stations = set([source])
        step = 0
        while queue:
            queue_len = len(queue)
            for i in range(queue_len):
                curr_station = queue.popleft()
                if curr_station == target:
                    return step
                for route in station_to_routes[curr_station] - visited_routes:
                    visited_routes.add(route)
                    for station in routes_to_stations[route] - visited_stations:
                        visited_stations.add(station)
                        queue.append(station)
            step += 1
        return -1
        
55026