I'm working on a graph theory problem with a given disconnected unweighted, undirected graph (given an edge list). The following operation can be made on the graph:
A set of edges represented by two vertex pairs (i, j) and (x, y) can be switched into (i, y) and (x, j)
The following are the tasks that need to be accomplished:
- Determine if it is possible to connect the graph.
- If yes, find the minimum number of operations to connect the graph.
- Output the edges used per operation in the following order:
i j x y
An additional constraint is that a vertex cannot be connected to itself. Vertices can be up to n = 10^5
I have already implemented the switch function defined above, however, my current solution is very inefficient and may not be applicable to all possible inputs. It basically checks for any four vertices with multiple connections and applies the switch operation, then runs a DFS (depth-first search) algorithm to check if the graph is connected or not, so it runs a DFS every time it makes an operation. Additionally, this doesn't deal with the minimum operations, it just does operations until the graph becomes connected. Are there any implementation tips or algorithms that can help in solving the problem, preferably in Python?