500个线路,10**6个车站,求s站到t站最少坐几条线
这道题分类很明显 BFS:无向无权图,最短路径
# 难点在于,数据规模较大,怎么处理临接表,怎么优化
两个思路:1 传统的,把车站作为图的节点;2 因为线路的数量少,可以把线路作为图的节点。
优化方面:访问过的车站,访问过的线路,都及时跳过,防止重复遍历
以车站为节点:
import queue
import collections
class StationInfo(object):
def __init__(self):
self.Steps = -1
self.Routes = list()
class Solution(object):
def numBusesToDestination0(self, routes, source, target):
"""
:type routes: List[List[int]]
:type source: int
:type target: int
:rtype: int
"""
if source == target :
return 0
bfsq = queue.SimpleQueue()
stations = collections.defaultdict(StationInfo) #[StationInfo for i in range(10**6)]
route_visited = [0] * len(routes)
for rid, r in enumerate(routes):
for sta in r:
stations[sta].Routes.append(rid)
stations[source].Steps = 0
bfsq.put(source)
while(not bfsq.empty()):
a = bfsq.get()
a_step = stations[a].Steps
for rid in stations[a].Routes:
if (route_visited[rid]): continue
route_visited[rid] = True
for b in routes[rid]:
if (b == target):
return a_step + 1
b_info = stations[b]
if(b_info.Steps >= 0): continue
b_info.Steps = a_step + 1
bfsq.put(b)
return -1
以路线为节点:
import queue
import collections
class Solution(object):
def numBusesToDestination(self, routes, source, target):
"""
:type routes: List[List[int]]
:type source: int
:type target: int
:rtype: int
"""
if source == target :
return 0
s_routes, t_routes = set(), set()
route_step = [-1 for _ in range(len(routes))]
for rid, r in enumerate(routes):
if source in r:
s_routes.add(rid)
route_step[rid] = 1
if target in r:
t_routes.add(rid)
routes[rid] = set(r)
if s_routes & t_routes: ## 如果有共同的路线连接
return 1
q = collections.deque(list(s_routes))
while q:
r1 = q.popleft()
r1_step = route_step[r1]
r2_step = r1_step + 1
for rid, r in enumerate(routes):
if (route_step[rid] < 0 and routes[r1] & r): ## 未访问过,且两条路线有相同站点
r2 = rid
if (r2 in t_routes):
return r2_step
route_step[r2] = r2_step
q.append(r2)
return -1