Sunday, 23 October 2016

Shortest Reach in a Graph (CTCI)

Problem: Shortest Reach in a Graph

class Graph {
    public:
        int node;
        vector<int> adj[1001];
        Graph(int n) {
            node = n;
        }
    
        void add_edge(int u, int v) {
            adj[u].push_back(v);
            adj[v].push_back(u);
        }
    
        vector<int> shortest_reach(int start) {
            vector<int> dist (node);
            for(int i=0;i<node;i++)
                dist[i]=-1;
            dist[start]=0;
            queue<int>Q;
            Q.push(start);
            while(!Q.empty())
            {
                int tmp = Q.front();
                for(int i=0;i<adj[tmp].size();i++)
                    if(dist[adj[tmp][i]]==-1)
                    {
                        dist[adj[tmp][i]] = dist[tmp]+6;
                        Q.push(adj[tmp][i]);
                    }
                Q.pop();
            }
            return dist;
        }
    
};

int main() {
    int queries;
    cin >> queries;
        
    for (int t = 0; t < queries; t++) {
      
      int n, m;
        cin >> n;
        // Create a graph of size n where each edge weight is 6: 
        Graph graph(n);
        cin >> m;
        // read and set edges
        for (int i = 0; i < m; i++) {
            int u, v;
            cin >> u >> v;
            u--, v--;
            // add each edge to the graph
            graph.add_edge(u, v);
        }
      int startId;
        cin >> startId;
        startId--;
        // Find shortest reach from node s
        vector<int> distances = graph.shortest_reach(startId);

        for (int i = 0; i < distances.size(); i++) {
            if (i != startId) {
                cout << distances[i] << " ";
            }
        }
        cout << endl;
    }
    
    return 0;
}

No comments:

Post a Comment