Ok, since the search for cycles in the graph of problems does not cause and suits the answer to C # (see the comments to the question), I will give a simple solution to the forehead. LiNQ is not used to simplify porting to Java, although it would be more compact with it.
We define a simple vertex class of an un-oriented graph (the necessary minimum):
class Vertex { public List<Vertex> Adges = new List<Vertex>(); public bool HasAdgeToVertex(Vertex vertex) { foreach(var adge in Adges) { if (adge == vertex) return true; } return false; } }
Now we need two functions to check that the vertices of the found cycle are the graph K5 or K3,3
Check for K5:
bool IsK5graph(Vertex[] subgraph) { bool result = false; int n = 5; if (subgraph.Length == n) { result = true; for (var i = 0; i < n - 1; i++) { for (var j = i + 1; j < n; j++) { result &= subgraph[i].HasAdgeToVertex(subgraph[j]); } } } return result; }
Simply check that for this set of vertices there are all 10 necessary edges.
Similarly for K3.3, but taking into account its features, we will slightly change the internal verification cycle:
bool IsK33graph(Vertex[] subgraph) { bool result = false; int n = 6; if (subgraph.Length == n) { result = true; for (var i = 0; i < n - 1; i++) { for (var j = i + 1; j < n; j += 2) { result &= subgraph[i].HasAdgeToVertex(subgraph[j]); } } } return result; }
Both checks are processed in N iterations, where N is the number of edges of the graph K5 and K3.3, respectively. Given the small N, optimizing the verification by reducing the number of iterations and complicating the verification code may not give any or even negative effect on the total time of the graph verification. But you can optimize the check for the presence of an edge at a vertex, for example, replacing a List for storing adjacent vertices, with a HashSet if the original graph does not contain parallel edges.
If we specify the edges through the adjacency matrix, then the matrix for K5 will look like this for an undirected graph:
1 2 3 4 5 --------- 1 | 0 1 1 1 1 | 2 | 1 0 1 1 1 | 3 | 1 1 0 1 1 | 4 | 1 1 1 0 1 | 5 | 1 1 1 1 0 |
Then the solution can be reduced to constructing an adjacency matrix for the vertices of the found cycle and checking that it does not coincide with the given one. In order to speed up the process, it is possible to combine the construction and verification of adjacency matrices for coincidence. If the main graph is specified via the adjacency matrix, then this option may be convenient.
For K3,3 the matrix is as follows:
1 2 3 4 5 6 ----------- 1 | 0 1 0 1 0 1 | 2 | 1 0 1 0 1 0 | 3 | 0 1 0 1 0 1 | 4 | 1 0 1 0 1 0 | 5 | 0 1 0 1 0 1 | 6 | 1 0 1 0 1 0 |