Leetcode 1129. Color Alternating Shortest Path BFS+ Simulation

Original title link: Leetcode 1129. The shortest path with alternating colors

insert image description here
insert image description here
Reference: The shortest path with alternating colors has a clear idea Based on basic BFS, it is easy to write and fully understand the meaning of the question

class Solution {
    
    
public:
    vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) {
    
    
        vector<vector<pair<int,int>>> g(n);
        vector<vector<int>> visit(n,vector<int>(2,0));
        for(auto x:redEdges)
        {
    
    
            int a=x[0],b=x[1];
            g[a].push_back({
    
    b,0});
        }
        for(auto x:blueEdges)
        {
    
    
            int a=x[0],b=x[1];
            g[a].push_back({
    
    b,1});
        }
        queue<vector<int>> q;
        vector<int> dis(n,INT_MAX);
        dis[0]=0;
        q.push({
    
    0,0,1});
        q.push({
    
    0,0,0});
        while(!q.empty())
        {
    
    
            auto tmp=q.front();
            int from=tmp[0];
            int d=tmp[1];
            int col=tmp[2];
            q.pop();
            for(auto x:g[from])
            {
    
    
                int to=x.first,color=x.second;
                if(col==(!color) && !visit[to][color]) 
                {
    
    
                    dis[to]=min(d+1,dis[to]);
                    q.push({
    
    to,d+1,color});
                    visit[to][color]=1;
                }
            }
        }
        for(int i=0;i<n;i++)
        {
    
    
            if(dis[i]==INT_MAX) dis[i]=-1;
        }
        return dis;
    }
};

Guess you like

Origin blog.csdn.net/qq_45791939/article/details/128105074