BFS: Shortest Reach in a Graph

  • + 0 comments

    include

    include

    include

    include

    include

    include

    using namespace std;

    class Graph { vector> adjList; int n;

    public:
        Graph(int n) {
            adjList = vector<vector<int>> (n);
            this->n = n;
        }
    
        void add_edge(int u, int v) {
            adjList[u].push_back(v);
            adjList[v].push_back(u);
        }
    
        vector<int> shortest_reach(int start) {
            vector<int> shortest_paths = vector<int>(n, -1);
    
            queue<int> q;
            q.push(start);
            vector<bool> visited(n);
            visited[start] = true;
            int curr_level = 1;
            while(q.size()){
                int level_size = q.size();
                while(level_size--){
                    int curr_node = q.front();
                    q.pop();
                    for(int adj_val: adjList[curr_node]){
                        if(!visited[adj_val]){
                            shortest_paths[adj_val] = curr_level * 6;
                            visited[adj_val] = true;
                            q.push(adj_val);
                        }
                    }
                }
                curr_level++;
            }
        return shortest_paths;
    }
    
            return shortest_paths;
        }
    

    };