在一个有向图中,节点分别标记为 0, 1, ..., n-1。这个图中的每条边不是红色就是蓝色,且存在自环或平行边。
red_edges 中的每一个 [i, j] 对表示从节点 i 到节点 j 的红色有向边。类似地,blue_edges 中的每一个 [i, j] 对表示从节点 i 到节点 j 的蓝色有向边。
返回长度为 n 的数组 answer,其中 answer[X] 是从节点 0 到节点 X 的红色边和蓝色边交替出现的最短路径的长度。如果不存在这样的路径,那么 answer[x] = -1。
示例 1:
输入:n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
输出:[0,1,-1]
示例 2:
输入:n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
输出:[0,1,-1]
示例 3:
输入:n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
输出:[0,-1,-1]
示例 4:
输入:n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
输出:[0,1,2]
示例 5:
输入:n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
输出:[0,1,1]
提示:
1 <= n <= 100
red_edges.length <= 400
blue_edges.length <= 400
red_edges[i].length == blue_edges[i].length == 2
0 <= red_edges[i][j], blue_edges[i][j] < n
思路:简单的广度优先搜素,我们首先将0加入队列,队列的每个元素要维护三个值,分别为:当前节点编号、走到当前位置所走的路径长度、上一条边是红边还是蓝边。之后直接按照一般思路遍历即可。
class Solution {
class node {
int nxt, val, id;
public node(int nxt, int val, int id) {
this.nxt = nxt;
this.val = val;
this.id = id;
}
}
public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) {
int[] dis = new int[n];
Queue q = new LinkedList<>();
boolean[][] flag = new boolean[n][2];
List> list_red = new ArrayList<>();
List> list_blue = new ArrayList<>();
for (int i = 0; i < n; i++) {
list_red.add(new ArrayList<>());
list_blue.add(new ArrayList<>());
}
for (int i = 0; i < red_edges.length; i++)
list_red.get(red_edges[i][0]).add(red_edges[i][1]);
for (int i = 0; i < blue_edges.length; i++)
list_blue.get(blue_edges[i][0]).add(blue_edges[i][1]);
Arrays.fill(dis, -1);
q.add(new node(0, 0, 0));
q.add(new node(0, 0, 1));
flag[0][0] = flag[0][1] = true;
while (!q.isEmpty()) {
node now = q.poll();
dis[now.nxt] = (dis[now.nxt] == -1 ? now.val : Math.min(dis[now.nxt], now.val));
if (now.id == 0) {
int size = list_blue.get(now.nxt).size();
for (int i = 0; i < size; i++) {
int nxt = list_blue.get(now.nxt).get(i);
if (!flag[nxt][1]) {
flag[nxt][1] = true;
q.add(new node(nxt, now.val + 1, 1 - now.id));
}
}
} else {
int size = list_red.get(now.nxt).size();
for (int i = 0; i < size; i++) {
int nxt = list_red.get(now.nxt).get(i);
if (!flag[nxt][0]) {
flag[nxt][0] = true;
q.add(new node(nxt, now.val + 1, 1 - now.id));
}
}
}
}
return dis;
}
}