TheAlgorithms/C-Sharp · error

n

Error message

n

What it means

BacktrackSolve validates the board size before solving the N-Queens problem. It throws ArgumentException when n is negative, because a negative dimension cannot form a bool[n,n] board. The parameter name is passed as the 'message', so the error text is just 'n'.

Solutions

  1. Pass a non-negative n (0 is allowed and yields an empty solution set).
  2. Validate n >= 0 at the call site before invoking.
  3. Fix the upstream calculation or config parsing that produced the negative value.

Example fix

// before
solver.BacktrackSolve(-1);
// after
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), n, "Must be >= 0");
var solutions = solver.BacktrackSolve(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), n, "Board size must be non-negative");

Type guard

static bool IsValidBoardSize(int n) => n >= 0;

Prevention

When it happens

Trigger: Calling BacktrackSolve with any negative integer, e.g. BacktrackSolve(-1) or a size computed from user input or a subtraction that underflows.

Common situations: User-supplied board size not validated upstream; computing n from a difference of lengths that came out negative; config default of -1 meaning 'unset' passed straight through.

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/7998482ab6344557. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Problems/NQueens/BacktrackingNQueensSolver.cs:15

namespace Algorithms.Problems.NQueens;

public class BacktrackingNQueensSolver
{
    /// <summary>
    ///     Solves N-Queen Problem given a n dimension chessboard and using backtracking with recursion algorithm.
    ///     If we find a dead-end within or current solution we go back and try another position for queen.
    /// </summary>
    /// <param name="n">Number of rows.</param>
    /// <returns>All solutions.</returns>
    public IEnumerable<bool[,]> BacktrackSolve(int n)
    {
        if (n < 0)
        {
            throw new ArgumentException(nameof(n));
        }

        return BacktrackSolve(new bool[n, n], 0);
    }

    private static IEnumerable<bool[,]> BacktrackSolve(bool[,] board, int col)
    {
        var solutions = col < board.GetLength(0) - 1
            ? HandleIntermediateColumn(board, col)
            : HandleLastColumn(board);
        return solutions;
    }

    private static IEnumerable<bool[,]> HandleIntermediateColumn(bool[,] board, int col)
    {
        // To start placing queens on possible spaces within the board.
        for (var i = 0; i < board.GetLength(0); i++)
        {

View on GitHub (pinned to 96e2905cab)