Breadth First Search: Shortest Reach

  • + 0 comments
    vector<int> bfs(int n, int m, vector<vector<int>> edges, int s) 
    {
        // Rearranging edges. my_edges[i] - a list of nodes connected with i-th node
        vector<vector<int>> my_edges(n);
         
        for (auto edge : edges)
        {
            my_edges[edge[0]-1].push_back(edge[1]);
            my_edges[edge[1]-1].push_back(edge[0]);
        }
     
        // Traversing through the graph
        queue<int> my_queue;
        my_queue.push(s);
        
        vector <int> distances(n, -1);
        distances[s-1] = 0;
        int current_dist = 0;
     
        
        while(!my_queue.empty())
        {
            int current_node = my_queue.front();
            
            for(int new_node : my_edges[current_node-1])
            {
                if ( distances[new_node-1] == -1 )
                {
                    my_queue.push(new_node);
                    distances[new_node-1] = distances[current_node-1] + 6;
                }
            }
            
            my_queue.pop();
        }
    
        // Removing the start node
        vector<int> ans;
        ans.reserve(n-1);
        
        for(int i = 0 ; i < n ; i++)
        {
            if (i != s-1)
                ans.push_back(distances[i]);
        }
    
        return ans;
    }