using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
List<
int
>
ShortestAlternateColoredPath(
int
n,
List<List<
int
> > redEdges,
List<List<
int
> > blueEdges)
{
List<
int
>[] graph =
new
List<
int
>[ 2 * n ];
for
(
int
i = 0; i < 2 * n; i++) {
graph[i] =
new
List<
int
>();
}
foreach
(
var
edge
in
redEdges)
{
graph[edge[0]].Add(edge[1]);
}
foreach
(
var
edge
in
blueEdges)
{
graph[edge[0] + n].Add(edge[1] + n);
}
int
[, ] distances =
new
int
[n, 2];
for
(
int
i = 0; i < n; i++) {
distances[i, 0] = distances[i, 1] = 2 * n;
}
distances[0, 0] = distances[0, 1] = 0;
Queue<Tuple<
int
,
int
> > bfsQueue
=
new
Queue<Tuple<
int
,
int
> >();
bfsQueue.Enqueue(
new
Tuple<
int
,
int
>(0, 0));
bfsQueue.Enqueue(
new
Tuple<
int
,
int
>(0, 1));
while
(bfsQueue.Count > 0) {
var
current = bfsQueue.Dequeue();
int
currentNode = current.Item1;
int
color = current.Item2;
foreach
(
var
next
in
graph[n * (1 - color) + currentNode])
{
if
(distances[next % n, 1 - color]
> distances[currentNode, color] + 1) {
distances[next % n, 1 - color]
= distances[currentNode, color] + 1;
bfsQueue.Enqueue(
new
Tuple<
int
,
int
>(
next % n, 1 - color));
}
}
}
List<
int
> result =
new
List<
int
>();
for
(
int
i = 0; i < n; i++) {
result.Add(
Math.Min(distances[i, 0], distances[i, 1]));
if
(result[i] == 2 * n)
result[i] = -1;
}
return
result;
}
public
static
void
Main(
string
[] args)
{
int
n = 3;
List<List<
int
> > redEdges
=
new
List<List<
int
> >{
new
List<
int
>{ 1, 0 } };
List<List<
int
> > blueEdges
=
new
List<List<
int
> >{
new
List<
int
>{ 0, 1 },
new
List<
int
>{ 0, 2 } };
List<
int
> result = ShortestAlternateColoredPath(
n, redEdges, blueEdges);
Console.WriteLine(
"Shortest Alternate Colored Path for each node:"
);
foreach
(
var
item
in
result)
{
Console.Write(item +
" "
);
}
Console.WriteLine();
}
}