1129. 颜色交替的最短路径(BFS)

在这里插入图片描述

class Solution {
    
    
    public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
    
    
        List<Integer>[][] edge = new List[2][n]; // edge[0][0] 表示与节点0相连的所有红边
                                             // edge[0][1] 表示与节点1相连的所有蓝边
        for(int i=0;i<2;i++) {
    
    
            for(int j=0;j<n;j++) {
    
    
                edge[i][j] = new ArrayList<>();
            }
        }
        for(int[] red:redEdges) {
    
    
            edge[0][red[0]].add(red[1]);
        }
        for(int[] blue:blueEdges) {
    
    
            edge[1][blue[0]].add(blue[1]);
        }
        int[][] dist = new int[2][n]; // dist[0][1] 表示0-1且边最终颜色为红色的最短路径
                                      // dist[1][1] 表示0-1且边最终颜色为蓝色的最短路径
        for(int i=0;i<2;i++) {
    
    
            Arrays.fill(dist[i], Integer.MAX_VALUE);
        }
        Queue<int[]> queue = new ArrayDeque<>(); // 队列的每一项代表{边颜色,节点}
        dist[0][0] = 0;
        dist[1][0] = 0;
        queue.offer(new int[]{
    
    0,0});
        queue.offer(new int[]{
    
    1,0});
        while(!queue.isEmpty()){
    
    
            int[] front = queue.poll();
            int x = front[0]; // 边颜色
            int y = front[1]; // 节点
            for(int t:edge[1-x][y]) {
    
     // 遍历节点y相连的,与上一条边颜色不同的所有点
                if(dist[1-x][t] != Integer.MAX_VALUE) // 已经到达过此点
                    continue;
                dist[1-x][t] = dist[x][y] + 1;
                queue.offer(new int[]{
    
    1-x, t});    
            }
        }
        int[] ans = new int[n];
        for(int i=0;i<n;i++) {
    
    
            ans[i] = Math.min(dist[0][i],dist[1][i]);
            if(ans[i]==Integer.MAX_VALUE)
                ans[i]=-1;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/henulmh/article/details/128855948