TheAlgorithms/C-Sharp · error

Specified argument was out of the range of valid values…

Error message

Specified argument was out of the range of valid values. (Parameter 'start')

What it means

SolveNearestNeighbor throws ArgumentOutOfRangeException when the start index is negative or >= n, since it must index into the matrix as the tour's starting city. Note the check happens after the square-matrix validation, using n = rows.

Solutions

  1. Pass a start index in [0, n-1]; convert 1-based IDs with start - 1.
  2. Clamp or validate start before calling.
  3. Fix the source (config/UI) that supplied the out-of-range start.

Example fix

// before
solver.SolveNearestNeighbor(m, cityId); // 1-based
// after
var r = TravelingSalesmanSolver.SolveNearestNeighbor(m, cityId - 1);
Defensive patterns

Strategy: validation

Validate before calling

if (start < 0 || start >= m.GetLength(0)) throw new ArgumentOutOfRangeException(nameof(start), start, "Start must index a city");

Try / catch

try { var r = TravelingSalesmanSolver.SolveNearestNeighbor(m, start); }
catch (ArgumentOutOfRangeException ex) { logger.LogError(ex, "Invalid start city"); }

Prevention

When it happens

Trigger: Calling SolveNearestNeighbor(matrix, start) with start < 0 or start >= matrix dimension, e.g. SolveNearestNeighbor(m, 5) on a 4-city matrix or start defaulted from a bad config.

Common situations: Hardcoded start index kept after shrinking the dataset; 1-based city IDs passed instead of 0-based indices; start read from user input without bounds checking.

Related errors


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

Appendix: source

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

    /// <summary>
    /// Solves the TSP using the nearest neighbor heuristic. This method builds a route by always visiting the nearest unvisited city next.
    /// This approach is much faster but may not find the optimal solution.
    /// </summary>
    /// <param name="distanceMatrix">A square matrix where element [i, j] represents the distance from city i to city j.</param>
    /// <param name="start">The starting city index.</param>
    /// <returns>A tuple containing the route (as an array of city indices) and the total distance.</returns>
    public static (int[] Route, double Distance) SolveNearestNeighbor(double[,] distanceMatrix, int start = 0)
    {
        int n = distanceMatrix.GetLength(0);
        if (n != distanceMatrix.GetLength(1))
        {
            throw new ArgumentException("Distance matrix must be square.");
        }

        if (start < 0 || start >= n)
        {
            throw new ArgumentOutOfRangeException(nameof(start));
        }

        var visited = new bool[n];
        List<int> route = [start];
        visited[start] = true;
        double totalDistance = 0;
        int current = start;
        for (int step = 1; step < n; step++)
        {
            double minDist = double.MaxValue;
            int next = -1;
            for (int j = 0; j < n; j++)
            {
                if (!visited[j] && distanceMatrix[current, j] < minDist)
                {
                    minDist = distanceMatrix[current, j];
                    next = j;
                }

View on GitHub (pinned to 96e2905cab)