Skip to content

There is an issue in DirectedWeightedGraph.RemoveVertex #368

@AKozak11

Description

@AKozak11

The current implementation sets the value of the Vertices array to null at the index of the vertex to be removed, and decrements the Count member. This adds a null entry to the array and keeps the index of all other vertices the same. Since Count is decremented, the last element in the array will be overwritten when adding a new vertex.

I made a simple update to the test case to show that the index of the last vertex before the Remove operation will have the same index as a newly added vertex after the Remove operation (Assert.AreNotEqual). The test case fails. This will clearly have consequences since the index is used for all other operations.

[Test]
        public void GraphRemoveVertexTest_Success()
        {
            var graph = new DirectedWeightedGraph<char>(10);
            var vertexA = graph.AddVertex('A');
            var vertexB = graph.AddVertex('B');
            var vertexC = graph.AddVertex('C');
            graph.AddEdge(vertexB, vertexA, 5);
            graph.AddEdge(vertexC, vertexA, 5);
            var neighborsB = graph.GetNeighbors(vertexB).ToList();
            var neighborsC = graph.GetNeighbors(vertexC).ToList();

            graph.RemoveVertex(vertexA);

            var vertexD = graph.AddVertex('D');
            Assert.AreNotEqual(vertexC.Index, vertexD.Index);
            
            neighborsB.Should().HaveCount(1);
            neighborsB[0].Should().Be(vertexA);
            neighborsC.Should().HaveCount(1);
            neighborsC[0].Should().Be(vertexA);
            graph.GetNeighbors(vertexB).Should().HaveCount(0);
            graph.GetNeighbors(vertexC).Should().HaveCount(0);

        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions