I don’t know your approach and I don’t know where to find your submision, so when you want to get check a code, you should paste it here (best way with ideone or similar thing).

But correct (and I think the easiest) way to do this is following. First create graph. In task you have graph oriented, but forget it and make each edge bidirectional. Now as you mentioned, you want to find number of components in this graph.

You can use Depth first search. Basically you want to label each vertex with label ‘visited’ or ‘unvisited’. At the begining all vertices are ‘unvisited’. Now iterate through all vertices. If you process ‘visited’ vertex, just continue. You already count this component. But if the vertex is ‘unvisited’, you want to visit each vertex in this component and add one to result.

So you can use recursive function with parameter vertex *v*, where we want to start. Now you look through all neighbours of vertex *v*. If the neighbour *w* is ‘visited’ you can ignore it, you have been there before. But when is ‘unvisited’ change it to ‘visited’ and call same function with parameter *w*.

```
void dfs(int v) {
visited[v] = true;
for(w in neighbours of v) {
if(visited[w] == false) dfs(w);
}
}
```

Simple, isn’t it? Number of iteration in which you call this function *dfs()* is result.