A solved graph with n vertices will be a complete graph kn with ½n(n-1) edges.
Flipping the state of a vertex will mean that the vertex becomes disconnected from the graph and there are two disconnected complete sub-graphs K1 and K(n-1) which have contain 0 and ½(n-1)(n-2) edges, respectively.
Flipping the state of other vertices will disconnect each of them from the complete sub-graph containing it and connect it to all the vertices of the other complete sub-graph. So, generally, if there are x vertices that have flipped state then there will be a two complete sub-graphs Kx and K(n-x) with ½x(x-1) and ½(n-x)(n-1-x) edges respectively for a total of m = ½n(n-1) - nx +x(x-1) edges.
If we know m and n then we can solve the quadratic equation to find the number of moves x required to solve the problem:
x = ( n - SQRT( 4m + 2n - n² ) ) / 2
If x is a non-integer then the puzzle is not solvable.
If x is an integer then the puzzle may be solvable in exactly x moves but an additional check is needed to see if there is are two disconnected complete sub-graphs Kx and K(n-x).
Algorithm:
- Calculate
x; if it is not an integer then the graph is not solvable. [Complexity: O(1)]
- Pick a random vertex:
- its degree should be either
(x-1) or (n-x-1); if it is not then the graph is not solvable.
- generate a list of all its adjacent vertices. [Complexity:
O(n)]
- perform a depth-first (or breadth-first) search from that vertex. [Complexity:
O(n+m)]
- if the number of edges visited is ½x(x-1) or ½(n-x)(n-1-x) (corresponding to the degree of the original vertex) and no vertices are visited that were not adjacent to the original then the sub-graph is complete and you know the graph is solvable; if either condition is not true then the graph is not solvable.
- To be certain you could do the same for the other sub-graph but it is unnecessary.
Examples:
The graph where n=4,m=2 with edges (1,2) and (3,4) is solvable since x = ( 4 - SQRT( 0 ) ) / 2 = 2, an integer, and there are two K2 disconnected sub-graphs.
The graph where n=4,m=3 with edges (1,2), (2,3), (3,4) has x = ( 4 - SQRT( 4 ) ) / 2 = 1, an integer, but there is only one, connected non-complete graph when there should be two disconnected K1 and K3 sub-graphs.