TheAlgorithms/C-Sharp · error

Distance matrix must be square.

Error message

Distance matrix must be square.

What it means

SolveBruteForce requires the distance matrix to be square (same number of rows and columns) because city count is derived from row count; a non-square matrix has inconsistent city indexing, so an ArgumentException is thrown.

Solutions

  1. Build/validate the matrix so rows == columns before calling.
  2. Sanitize the source data (drop header rows/extra columns) when loading.
  3. Add a pre-call assertion that distanceMatrix.GetLength(0) == GetLength(1).

Example fix

// before
var result = TravelingSalesmanSolver.SolveBruteForce(rectangularMatrix);
// after
if (m.GetLength(0) != m.GetLength(1)) throw new ArgumentException("Distance matrix must be square");
var result = TravelingSalesmanSolver.SolveBruteForce(m);
Defensive patterns

Strategy: validation

Validate before calling

bool isSquare = m != null && m.Rank == 2 && m.GetLength(0) == m.GetLength(1);

Type guard

static bool IsSquareMatrix(double[,] m) => m.Rank == 2 && m.GetLength(0) == m.GetLength(1);

Try / catch

try { var r = TravelingSalesmanSolver.SolveBruteForce(m); }
catch (ArgumentException ex) { logger.LogError(ex, "Distance matrix not square"); }

Prevention

When it happens

Trigger: Passing a rectangular double[,] such as a 3x4 matrix, or a matrix built from m x n input where rows and cities were mixed up.

Common situations: Parsing a distance CSV with a trailing header column or extra column; constructing the matrix with [cities, edges] by mistake; merging datasets of different sizes.

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/67a13abe4002c246. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs:20

/// <summary>
/// Provides methods to solve the Traveling Salesman Problem (TSP) using brute-force and nearest neighbor heuristics.
/// The TSP is a classic optimization problem in which a salesman must visit each city exactly once and return to the starting city, minimizing the total travel distance.
/// </summary>
public static class TravelingSalesmanSolver
{
    /// <summary>
    /// Solves the TSP using brute-force search. This method checks all possible permutations of cities to find the shortest possible route.
    /// WARNING: This approach is only feasible for small numbers of cities due to factorial time complexity.
    /// </summary>
    /// <param name="distanceMatrix">A square matrix where element [i, j] represents the distance from city i to city j.</param>
    /// <returns>A tuple containing the minimal route (as an array of city indices) and the minimal total distance.</returns>
    public static (int[] Route, double Distance) SolveBruteForce(double[,] distanceMatrix)
    {
        int n = distanceMatrix.GetLength(0);
        if (n != distanceMatrix.GetLength(1))
        {
            throw new ArgumentException("Distance matrix must be square.");
        }

        if (n < 2)
        {
            throw new ArgumentException("At least two cities are required.");
        }

        var cities = Enumerable.Range(0, n).ToArray();
        double minDistance = double.MaxValue;
        int[]? bestRoute = null;

        foreach (var perm in Permute(cities.Skip(1).ToArray()))
        {
            var route = new int[n + 1];
            route[0] = 0;
            for (int i = 0; i < perm.Length; i++)
            {
                route[i + 1] = perm[i];

View on GitHub (pinned to 96e2905cab)