【Leetcode】1129. Shortest Path with Alternating Colors

Subject address:

https://leetcode.com/problems/shortest-path-with-alternating-colors/

Given a nnn- order directed graph, the vertex number is0 ∼ n − 1 0\sim n-10n1. Each side has a color, either red or blue. Returns an arrayAAA such thatA [k] A[k]A [ k ] is from0 00 to vertexkkIn the path of k , the length of the path with the shortest length and different adjacent sides. If you can't go, assign it to− 1 -11

The idea is BFS. In the BFS graph, it is necessary to add a dimension state, that is, what is the color of the edge that is taken before reaching a certain vertex. We can imagine that BFS is performed on an implicit graph of an expanded state. Each state has two properties: vertex number and edge color (the reason why the vertices of the implicit graph can be specified this way is because of any original graph The shortest path of and the shortest path of an implicit graph have a one-to-one correspondence and the path length is equal. The key reason is that all the red edges of a vertex in the shortest path of the original graph will go at most one of them, and the blue edges are similar. This can be proved by contradiction, if in the shortest path of a certain original graph, the red edge of a vertex goes two, then the first red edge and the second red edge can be the next blue edge Remove all the sides in between, so that you can get a shorter short circuit, which is contradictory). code show as below:

import java.util.*;

public class Solution {
    
    
    public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) {
    
    
    	// 用邻接表建图
        Map<Integer, List<Integer>>[] maps = (Map<Integer, List<Integer>>[]) (new HashMap[2]);
        maps[0] = new HashMap<>();
        maps[1] = new HashMap<>();
        for (int[] red_edge : red_edges) {
    
    
            int from = red_edge[0], to = red_edge[1];
            maps[0].putIfAbsent(from, new ArrayList<>());
            maps[0].get(from).add(to);
        }
        for (int[] blue_edge : blue_edges) {
    
    
            int from = blue_edge[0], to = blue_edge[1];
            maps[1].putIfAbsent(from, new ArrayList<>());
            maps[1].get(from).add(to);
        }
        
        int[] res = new int[n];
        Arrays.fill(res, -1);
        
        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{
    
    0, -1});
        res[0] = 0;
        
        // visited[i][0]指的是从红色边到达顶点i的这个状态有没有经历过
        boolean[][] visited = new boolean[n][2];
        
        int step = 0;
        while (!queue.isEmpty()) {
    
    
            step++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
    
    
                int[] cur = queue.poll();
                int pos = cur[0], color = cur[1];
                // 枚举下面一条路径的颜色
                for (int j = 0; j < 2; j++) {
    
    
                	// 如果颜色与上一条边颜色相同,则略过
                    if (j == color) {
    
    
                        continue;
                    }
    
                    if (maps[j].containsKey(pos)) {
    
    
                        for (int next : maps[j].get(pos)) {
    
    
                            if (!visited[next][j]) {
    
    
                                queue.offer(new int[]{
    
    next, j});
                                visited[next][j] = true;
                                // 第一次访问到next的时候就是最短距离
                                if (res[next] == -1) {
    
    
                                    res[next] = step;
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return res;
    }
}

Time and space complexity O (V + E) O(V+E)O ( V+E)

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/112761089