{"record":{"id":"67a13abe4002c246","repo":"TheAlgorithms/C-Sharp","slug":"distance-matrix-must-be-square","errorCode":null,"errorMessage":"Distance matrix must be square.","messagePattern":"Distance matrix must be square\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs","lineNumber":20,"sourceCode":"\n/// <summary>\n/// Provides methods to solve the Traveling Salesman Problem (TSP) using brute-force and nearest neighbor heuristics.\n/// 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.\n/// </summary>\npublic static class TravelingSalesmanSolver\n{\n    /// <summary>\n    /// Solves the TSP using brute-force search. This method checks all possible permutations of cities to find the shortest possible route.\n    /// WARNING: This approach is only feasible for small numbers of cities due to factorial time complexity.\n    /// </summary>\n    /// <param name=\"distanceMatrix\">A square matrix where element [i, j] represents the distance from city i to city j.</param>\n    /// <returns>A tuple containing the minimal route (as an array of city indices) and the minimal total distance.</returns>\n    public static (int[] Route, double Distance) SolveBruteForce(double[,] distanceMatrix)\n    {\n        int n = distanceMatrix.GetLength(0);\n        if (n != distanceMatrix.GetLength(1))\n        {\n            throw new ArgumentException(\"Distance matrix must be square.\");\n        }\n\n        if (n < 2)\n        {\n            throw new ArgumentException(\"At least two cities are required.\");\n        }\n\n        var cities = Enumerable.Range(0, n).ToArray();\n        double minDistance = double.MaxValue;\n        int[]? bestRoute = null;\n\n        foreach (var perm in Permute(cities.Skip(1).ToArray()))\n        {\n            var route = new int[n + 1];\n            route[0] = 0;\n            for (int i = 0; i < perm.Length; i++)\n            {\n                route[i + 1] = perm[i];","sourceCodeStart":2,"sourceCodeEnd":38,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs#L2-L38","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Build/validate the matrix so rows == columns before calling.","Sanitize the source data (drop header rows/extra columns) when loading.","Add a pre-call assertion that distanceMatrix.GetLength(0) == GetLength(1)."],"exampleFix":"// before\nvar result = TravelingSalesmanSolver.SolveBruteForce(rectangularMatrix);\n// after\nif (m.GetLength(0) != m.GetLength(1)) throw new ArgumentException(\"Distance matrix must be square\");\nvar result = TravelingSalesmanSolver.SolveBruteForce(m);","handlingStrategy":"validation","validationCode":"bool isSquare = m != null && m.Rank == 2 && m.GetLength(0) == m.GetLength(1);","typeGuard":"static bool IsSquareMatrix(double[,] m) => m.Rank == 2 && m.GetLength(0) == m.GetLength(1);","tryCatchPattern":"try { var r = TravelingSalesmanSolver.SolveBruteForce(m); }\ncatch (ArgumentException ex) { logger.LogError(ex, \"Distance matrix not square\"); }","preventionTips":["Sanitize CSV/TSV inputs of header rows and trailing columns","Use a single matrix-builder utility for all TSP solvers","Assert matrix shape in data-loading tests"],"tags":["argument-validation","csharp","tsp"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}