What is the wrong in this code?

I try to solve Connected Components problem using adjacency matrix. But get TLE .Please help me.

My Code

There’s nothing wrong with your solution, the reason for TLE is that your each DFS call is recursing DFS function when using adjacency matrix for each index from 0 to n - 1. That’s why we use a Adjacency List to reduce those iterations only for the connected nodes.

1 Like

How can i use adjacency matrix in this problem?
I try to 2d array argument but get RTE. code : http://ideone.com/ZD5qBm

I do not believe there is any way in that time constraint. DFS algorithm is having O(V2) complexity in adjacency matrix representation and O(V+E) in adjacency list representations. Suppose a node is not connected to any other nodes yet it will traverse O(V) while in adjacency list it would be O(1). Hope it helps now. Always try using adjacency list it maintains efficiency.