2023-02-11 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 11
Description
Shortest Path with Alternating Colors
You are given an integer n
, the number of nodes in a directed graph where the nodes are labeled from 0
to n - 1
. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
You are given two arrays redEdges
and blueEdges
where:
redEdges[i] = [ai, bi]
indicates that there is a directed red edge from nodeai
to nodebi
in the graph, andblueEdges[j] = [uj, vj]
indicates that there is a directed blue edge from nodeuj
to nodevj
in the graph.
Return an array answer
of length n
, where each answer[x]
is the length of the shortest path from node 0
to node x
such that the edge colors alternate along the path, or -1
if such a path does not exist.
Example 1:
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1]
Example 2:
Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] Output: [0,1,-1]
Constraints:
1 <= n <= 100
0 <= redEdges.length, blueEdges.length <= 400
redEdges[i].length == blueEdges[j].length == 2
0 <= ai, bi, uj, vj < n
Solution
class Solution {
public:
vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) {
vector<vector<int>> neighbors[2];
neighbors[0].resize(n);
neighbors[1].resize(n);
for(const auto &redEdge : redEdges) {
neighbors[0][redEdge[0]].push_back(redEdge[1]);
}
for(const auto &blueEdge : blueEdges) {
neighbors[1][blueEdge[0]].push_back(blueEdge[1]);
}
vector<int> distance[2];
distance[0].resize(n, INT_MAX);
distance[1].resize(n, INT_MAX);
queue<pair<int, int>> q;
q.push({0, 0});
q.push({0, 1});
distance[0][0] = 0;
distance[1][0] = 0;
int current = 0;
while(q.size()) {
int sz = q.size();
for(int _ = 0; _ < sz; ++_) {
auto [pos, color] = q.front();
q.pop();
for(auto next : neighbors[!color][pos]) {
if(distance[!color][next] != INT_MAX) continue;
distance[!color][next] = current + 1;
q.push({next, !color});
}
}
current += 1;
}
for(int i = 0; i < n; ++i) {
distance[0][i] = min(distance[0][i], distance[1][i]);
if(distance[0][i] == INT_MAX) {
distance[0][i] = -1;
}
}
return distance[0];
}
};
// Accepted
// 90/90 cases passed (15 ms)
// Your runtime beats 95.27 % of cpp submissions
// Your memory usage beats 89.64 % of cpp submissions (14.7 MB)