TheAlgorithms/C-Sharp · error · ArgumentException

Matrix must be square!

Error message

Matrix must be square!

What it means

Kruskal's minimum-spanning-tree solver requires the graph as a square adjacency matrix (vertices x vertices). ValidateGraph throws ArgumentException("Matrix must be square!") when adj.GetLength(0) != adj.GetLength(1) (Kruskal.cs:131). A non-square matrix cannot represent a weighted undirected graph, so the input is rejected before the algorithm runs.

Solutions

  1. Verify the matrix dimensions before calling Solve: adj.GetLength(0) == adj.GetLength(1).
  2. Fix the matrix construction so each of the n vertices has exactly n entries (row i column j = edge weight i->j).
  3. If data is rectangular, reshape or pad it into a square adjacency matrix (using infinity/no-edge sentinels for absent edges).

Example fix

// before
var adj = new float[numEdges, numVertices]; // rectangular
Kruskal.Solve(adj);
// after
var n = numVertices;
var adj = new float[n, n];
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        adj[i, j] = weightBetween(i, j); // e.g. float.PositiveInfinity when no edge
Kruskal.Solve(adj);
Defensive patterns

Strategy: validation

Validate before calling

if (adj.Rank != 2 || adj.GetLength(0) != adj.GetLength(1))
    throw new ArgumentException($"Adjacency matrix must be square, got {adj.GetLength(0)}x{adj.GetLength(1)}");
Kruskal.Solve(adj);

Type guard

static bool IsSquareMatrix(float[,]? m) => m is not null && m.Rank == 2 && m.GetLength(0) == m.GetLength(1);

Try / catch

try
{
    var mst = Kruskal.Solve(adj);
}
catch (ArgumentException ex) when (ex.Message.Contains("square"))
{
    logger.LogError(ex, "Adjacency matrix shape {Rows}x{Cols} is not square", adj.GetLength(0), adj.GetLength(1));
}

Prevention

When it happens

Trigger: Calling Kruskal.Solve with a rectangular float[,] — e.g. a matrix built from data rows x feature columns, an adjacency list flattened into a matrix, or a matrix missing its last row/column after truncation.

Common situations: Loading a CSV/TSV where a row has a different column count than the row count, slicing an adjacency matrix and producing a rectangle, or constructing the matrix as [edges, vertices] instead of [vertices, vertices].

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/7860afab9f96255a. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Graph/MinimumSpanningTree/Kruskal.cs:131

        foreach (var (node1, node2) in edges)
        {
            mst[node1].Add(node2, adjacencyList[node1][node2]);
            mst[node2].Add(node1, adjacencyList[node1][node2]);
        }

        return mst;
    }

    /// <summary>
    ///     Ensure that the given graph is undirected.
    /// </summary>
    /// <param name="adj">Adjacency matrix of graph to check.</param>
    private static void ValidateGraph(float[,] adj)
    {
        if (adj.GetLength(0) != adj.GetLength(1))
        {
            throw new ArgumentException("Matrix must be square!");
        }

        for (var i = 0; i < adj.GetLength(0) - 1; i++)
        {
            for (var j = i + 1; j < adj.GetLength(1); j++)
            {
                if (Math.Abs(adj[i, j] - adj[j, i]) > 1e-6)
                {
                    throw new ArgumentException("Matrix must be symmetric!");
                }
            }
        }
    }

    /// <summary>
    ///     Ensure that the given graph is undirected.
    /// </summary>
    /// <param name="adj">Adjacency list of graph to check.</param>

View on GitHub (pinned to 96e2905cab)