Breadth First Search: Shortest Reach

  • + 0 comments
    vector<int> bfs(int n, int m, vector<vector<int>> edges, int s) {
        int i, weight = 6;
        int visited[n];
        int sv, ev;
        vector<int> distance(n); // Store the distances to all nodes from start node, including start node
        queue<int> q; q.push(s);
        
        for (i = 0; i < n; ++i) {
            visited[i] = distance[i] = 0;
        }
        
        while (!q.empty()) {
            int w = q.front(); q.pop();
            if (!visited[w-1]) visited[w-1] = 1;
    
            // Search for edges that connect current node
            for (i = 0; i < edges.size(); ++i) {
                sv = edges[i][0];
                ev = edges[i][1];
                // The distance to the other node from start node is the distance to the current node from start node  +  weight
                if (sv == w) {
                    if (!visited[ev-1]) {
                        visited[ev-1] = 1;
                        q.push(ev);
                        distance[ev-1] += distance[sv-1] + weight;
                    } 
                } else if (ev == w) {
                    if (!visited[sv-1]) {
                        visited[sv-1] = 1;
                        q.push(sv);
                        distance[sv-1] += distance[ev-1] + weight;
                    } 
                }
            }
        }
    
        // Delete the start node from distance table
        distance.erase(distance.begin() + (s - 1));
        
        // If the distance from start node to a node is 0, then there is no connection between the two.  
        for (int n = 0; n < distance.size(); ++n) {
            if (distance[n] == 0)
                distance[n] = -1;
        }
        
        return distance;
    }