Puzzle in Interview

Problem: You have N computers and [Ca, Cb] means a is connected to b and this connectivity is symmetric and transitive. Write a program which checks that all computers are interconnected and talk to each other.

Solution: BFS. Since graph is connected, there will be path from every node to another. 
Algorithm:

BFS(V)
     VISITED(V) =1;
     Add(V,Q);
     while(Q is not empty)
               x= Delete(Q);
               for all W adjacent x
                     if(W is not visited)
                            Visited(W) = 1;
                            Add(W,Q);

Implementation in C: BFS

Time complexity: O(V + (V-1)V ) = O(V^2)


Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function