Once I worked through the cause and effect, it was less of a problem than I thought.
Let's look at the source code in the editorial and prove it.
Let's call the edges we need to add indirect edges (meaning they're connected indirectly)
and call the edges that already existed direct edges.
First, the direct edges are guaranteed to all be given without duplicates when the problem is given.
Then, running bfs or dfs from each node, we count all the nodes that are directly or indirectly connected.
Here, if we call the node bfs starts from x,
the number of nodes directly connected to x is equal to the number of directly connected nodes.
And the directly connected nodes are inevitably all found while running bfs.
And the problem says to add edges connecting a and c, which are indirectly connected,
which is the same as saying to add edges that directly connect a and c.
So the total number of nodes found while running bfs
equals the number of direct edges (M) plus the number of nodes that directly connect the indirectly connected nodes.
Count all of them and subtract M, and that's the answer.