'How to check if an undirected graph as adjacency list is valid?
There is an undirected graph class that can be initialized with an already existing adjacency list. On the constructor, it should check if the given adjacency list is correct. For example, the following data should not be accepted:
v1: [v2, v3]
v2: [v1, v3, v4]
v3: [v2] // should be [v1, v2]
v4: [v2]
There is an edge from v1 to v3 but not vice versa.
It currently attempts to check the integrity of the adjacency list with the following code.
public UndirectedGraph(Dictionary<int, List<int>> vertices)
{
foreach (var vertex in vertices)
{
foreach (var neighbour in vertex.Value)
{
if (!vertices[neighbour].Contains(vertex.Key))
throw new Exception("Graph is not undirected");
}
}
this.VertexList = vertices;
}
However, there is a problem. This class should allow multiple edges between the same vertices and the constructor accepts the following adjacency list when it shouldn't:
v1: [v2, v3, v3]
v2: [v1, v3, v4]
v3: [v1, v2] // should be [v1, v1, v2]
v4: [v2]
How to effectively check the validity of the passed parameter?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
