Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bus-routes.cpp 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-04-08 17:49 +08:00 . Update bus-routes.cpp
// Time: O(|V| + |E|)
// Space: O(|V| + |E|)
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
if (S == T) {
return 0;
}
unordered_map<int, unordered_set<int>> to_route;
for (int i = 0; i < routes.size(); ++i) {
for (const auto& stop : routes[i]) {
to_route[stop].emplace(i);
}
}
int result = 1;
vector<int> q{S};
unordered_set<int> lookup{S};
while (!q.empty()) {
vector<int> next_q;
for (const auto& stop : q) {
for (const auto& i : to_route[stop]) {
for (const auto& next_stop : routes[i]) {
if (lookup.count(next_stop)) {
continue;
}
if (next_stop == T) {
return result;
}
next_q.emplace_back(next_stop);
to_route[next_stop].erase(i);
lookup.emplace(next_stop);
}
}
}
swap(q, next_q);
++result;
}
return -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助