{"record":{"id":"36f36972a397a6e5","repo":"TheAlgorithms/C-Sharp","slug":"no-unvisited-cities-remain","errorCode":null,"errorMessage":"No unvisited cities remain.","messagePattern":"No unvisited cities remain\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs","lineNumber":100,"sourceCode":"        visited[start] = true;\n        double totalDistance = 0;\n        int current = start;\n        for (int step = 1; step < n; step++)\n        {\n            double minDist = double.MaxValue;\n            int next = -1;\n            for (int j = 0; j < n; j++)\n            {\n                if (!visited[j] && distanceMatrix[current, j] < minDist)\n                {\n                    minDist = distanceMatrix[current, j];\n                    next = j;\n                }\n            }\n\n            if (next == -1)\n            {\n                throw new InvalidOperationException(\"No unvisited cities remain.\");\n            }\n\n            route.Add(next);\n            visited[next] = true;\n            totalDistance += minDist;\n            current = next;\n        }\n\n        totalDistance += distanceMatrix[current, start];\n        route.Add(start);\n        return (route.ToArray(), totalDistance);\n    }\n\n    /// <summary>\n    /// Generates all permutations of the input array.\n    /// Used for brute-force TSP solution.\n    /// </summary>\n    private static IEnumerable<int[]> Permute(int[] arr)","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs#L82-L118","documentation":"SolveNearestNeighbor throws InvalidOperationException when no unvisited city can be found for the next hop (next == -1) before the tour covers all cities. Under normal input this is unreachable — it fires only if the matrix contains values the search cannot consume (e.g. NaN or infinity distances) so no candidate ever wins the minimum scan.","triggerScenarios":"A square matrix containing double.NaN or double.PositiveInfinity entries such that every unvisited city is 'worse' than the sentinel, leaving next at -1 mid-tour.","commonSituations":"Missing/unknown pairwise distances represented as NaN; disconnected graph encoded as infinity; matrix built by formula producing NaN (0/0, sqrt of negative).","solutions":["Sanitize the matrix: replace NaN/Infinity with large finite values or handle disconnected pairs explicitly.","Validate all entries are finite doubles before calling.","If the graph is genuinely disconnected, use a TSP variant that supports it instead of the plain nearest-neighbor solver."],"exampleFix":"// before\nfor (int i=0;i<n;i++) for (int j=0;j<n;j++) if (double.IsNaN(m[i,j])) m[i,j] = double.PositiveInfinity;\nsolver.SolveNearestNeighbor(m);\n// after\nfor (int i=0;i<n;i++) for (int j=0;j<n;j++) if (!double.IsFinite(m[i,j])) m[i,j] = 1e9;\nvar r = solver.SolveNearestNeighbor(m);","handlingStrategy":"validation","validationCode":"for (int i = 0; i < m.GetLength(0); i++)\n    for (int j = 0; j < m.GetLength(1); j++)\n        if (!double.IsFinite(m[i, j])) throw new ArgumentException($\"Non-finite distance at [{i},{j}]\");","typeGuard":null,"tryCatchPattern":"try { var r = TravelingSalesmanSolver.SolveNearestNeighbor(m, start); }\ncatch (InvalidOperationException ex) { logger.LogError(ex, \"Solver could not progress; check for NaN/Infinity distances\"); }","preventionTips":["Replace NaN/Infinity with large finite sentinel distances","Validate matrix finiteness after loading","Treat disconnected graphs with an algorithm that supports them"],"tags":["invariant","csharp","tsp","nan"],"backgroundTag":"internal-invariant-violation","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"}