Since this distance learning thing started I've really struggled to understand data structures and this question really threw me for a loop. I have absolutely no idea how to even start with the code let alone get my point across. Any help at all would be much appreciated...
-
In your example the components are not linked to each other. If that is the case you can find such island (component) using BFS , remove the component from the graph and search for the next one. – c0der Apr 25 '20 at 10:16
1 Answers
Pick any node in the graph. That node belongs to some component, and it’s there with potentially a few other nodes. So run a BFS, painting that node and everything reachable from it gold. That’s one component.
Now pick another node. One of two things must be true about it. First, it could be the case that the node has already been painted gold. In that case, you already have counted the component that contains it. Second, it could be unpainted. In that case, you haven’t counted its component, so paint it and all nodes reachable from it gold, and that’s your second component.
Do you think you can generalize this idea so that you count all the components?
As for runtime - how many times does each node get visited this way? Remember that you only paint each node gold once and that each edge is only visited in the course or painting nodes.

- 362,284
- 104
- 897
- 1,065