2023-11-12 Daily Challenge
Today I have done leetcode's November LeetCoding Challenge with cpp
.
November LeetCoding Challenge 12
Description
Bus Routes
You are given an array routes
representing bus routes where routes[i]
is a bus route that the ith
bus repeats forever.
- For example, if
routes[0] = [1, 5, 7]
, this means that the0th
bus travels in the sequence1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...
forever.
You will start at the bus stop source
(You are not on any bus initially), and you want to go to the bus stop target
. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source
to target
. Return -1
if it is not possible.
Example 1:
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Example 2:
Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1
Constraints:
1 <= routes.length <= 500
.1 <= routes[i].length <= 105
- All the values of
routes[i]
are unique. sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if(source == target) return 0;
map<int, vector<int>> stopRoutes;
for(int i = 0; i < routes.size(); ++i) {
for(auto bus : routes[i]) {
stopRoutes[bus].push_back(i);
}
}
vector<bool> visitRoutes(routes.size());
set<int> visitStop;
queue<int> q;
for(auto route : stopRoutes[source]) {
q.push(route);
}
int count = 1;
while(q.size()) {
int sz = q.size();
for(int _ = 0; _ < sz; ++_) {
auto route = q.front();
q.pop();
if(visitRoutes[route]) continue;
visitRoutes[route] = true;
for(auto stop : routes[route]) {
if(stop == target) return count;
if(visitStop.count(stop)) continue;
for(auto route : stopRoutes[stop]) {
q.push(route);
}
visitStop.insert(stop);
}
}
count += 1;
}
return -1;
}
};
// Accepted
// 49/49 cases passed (293 ms)
// Your runtime beats 60.83 % of cpp submissions
// Your memory usage beats 41.02 % of cpp submissions (72.5 MB)