TheAlgorithms/C-Sharp · error · ArgumentException

Adjacency matrix must be square!

Error message

Adjacency matrix must be square!

What it means

Prim's MST algorithm (matrix variant) requires the adjacency matrix to be square: the element at [i,j] must be defined for all pairs of the same set of nodes, so GetLength(0) must equal GetLength(1). ValidateMatrix, invoked from Solve, throws ArgumentException when the two dimensions differ. A non-square matrix cannot represent a complete node-to-node weight table.

Solutions

  1. Ensure the array is created as new float[n, n] where n is the node count, with both dimensions equal.
  2. Audit how the matrix is built; if you have an edge list, first convert it into a square n x n adjacency matrix.
  3. Check for transposed/rectangular intermediate arrays and use a proper 2D square matrix for graph data.
  4. Pre-validate in your own code: matrix.GetLength(0) == matrix.GetLength(1) before calling Solve.

Example fix

// before
var adj = new float[nodeCount, edgeCount];

// after
var adj = new float[nodeCount, nodeCount]; // must be square
Defensive patterns

Strategy: validation

Validate before calling

static bool IsSquare(float[,] m) => m != null && m.GetLength(0) == m.GetLength(1);
if (!IsSquare(adj)) throw new ArgumentException("adjacency matrix must be square");

Type guard

static bool IsSquareMatrix(float[,] m) => m != null && m.GetLength(0) == m.GetLength(1);

Try / catch

try
{
    var mst = prim.Solve(adj);
}
catch (ArgumentException ex) when (ex.Message == "Adjacency matrix must be square!")
{
    // rebuild as n x n matrix before retrying
}

Prevention

When it happens

Trigger: Calling PrimMatrix.Solve with a float[,] whose first and second dimensions differ — e.g. constructing a rows x edges or nodes x (nodes-1) array, or accidentally transposing part of a rectangular array.

Common situations: Initializing the array with swapped dimension arguments (new float[n, m] instead of new float[n, n]); representing an edge list or incidence matrix instead of an adjacency matrix; resizing the node count but updating only one dimension.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/49c808879f20d4c8. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs:83

            }

            mst[i, parent[i]] = adjacencyMatrix[i, parent[i]];
            mst[parent[i], i] = adjacencyMatrix[i, parent[i]];
        }

        return mst;
    }

    /// <summary>
    ///     Ensure that the given adjacency matrix represents a weighted undirected graph.
    /// </summary>
    /// <param name="adjacencyMatrix">Adjacency matric to check.</param>
    private static void ValidateMatrix(float[,] adjacencyMatrix)
    {
        // Matrix should be square
        if (adjacencyMatrix.GetLength(0) != adjacencyMatrix.GetLength(1))
        {
            throw new ArgumentException("Adjacency matrix must be square!");
        }

        // Graph needs to be undirected and connected
        for (var i = 0; i < adjacencyMatrix.GetLength(0); i++)
        {
            var connection = false;
            for (var j = 0; j < adjacencyMatrix.GetLength(0); j++)
            {
                if (Math.Abs(adjacencyMatrix[i, j] - adjacencyMatrix[j, i]) > 1e-6)
                {
                    throw new ArgumentException("Adjacency matrix must be symmetric!");
                }

                if (!connection && float.IsFinite(adjacencyMatrix[i, j]))
                {
                    connection = true;
                }
            }

View on GitHub (pinned to 96e2905cab)