TheAlgorithms/C-Sharp · error
Number of colors must be positive.
Error message
Number of colors must be positive.
What it means
This ArgumentException is the numColors parameter check at the top of GraphColoringSolver.ColorGraph (GraphColoringSolver.cs:83), after the null-matrix and square-matrix checks. Graph coloring needs at least one color available; a numColors of zero or negative would make backtracking search impossible for any non-empty graph. It fires whenever ColorGraph is called with numColors <= 0.
Solutions
- Pass at least 1 as numColors.
- Clamp/validate: if (k < 1) k = 1; or reject earlier with a clearer message.
- Resolve the config/default handling that produced a non-positive k.
Example fix
// before var k = config.MaxColors; // may be 0 var colors = solver.ColorGraph(matrix, k); // after var k = Math.Max(1, config.MaxColors); var colors = solver.ColorGraph(matrix, k);
Defensive patterns
Strategy: validation
Validate before calling
if (numColors < 1) throw new ArgumentException("numColors must be >= 1.", nameof(numColors)); Try / catch
try { colors = solver.ColorGraph(matrix, k); }
catch (ArgumentException ex) { Console.Error.WriteLine(ex.Message); } Prevention
- Clamp color counts with Math.Max(1, k)
- Treat 0 as 'auto' in config and resolve before calling
- Validate config-derived integers at load time
When it happens
Trigger: Calling ColorGraph(matrix, 0) or ColorGraph(matrix, -1); passing an uninitialized/failed computation result as the color count.
Common situations: Computing k from user configuration where 0 means 'auto' but is passed through unchanged; integer parse of an empty field yielding 0; sign errors in derived limits.
Related errors
- k must be at least 1.
- Board size must be positive.
- Load factor must be greater than 0
- Load factor must be less than or equal to 1
- Invalid block size
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/2013e933524e3d8b.
Report an issue: GitHub.
Appendix: source
Thrown at Algorithms/Problems/GraphColoring/GraphColoringSolver.cs:83
/// </para>
/// </remarks>
public int[] ColorGraph(bool[,] adjacencyMatrix, int numColors)
{
if (adjacencyMatrix is null)
{
throw new ArgumentNullException(nameof(adjacencyMatrix));
}
var numVertices = adjacencyMatrix.GetLength(0);
if (numVertices != adjacencyMatrix.GetLength(1))
{
throw new ArgumentException("Adjacency matrix must be square.", nameof(adjacencyMatrix));
}
if (numColors <= 0)
{
throw new ArgumentException("Number of colors must be positive.", nameof(numColors));
}
// Handle empty graph
if (numVertices == 0)
{
return Array.Empty<int>();
}
var colors = new int[numVertices];
// Initialize all vertices as uncolored (-1)
Array.Fill(colors, -1);
if (!ColorVertex(adjacencyMatrix, colors, 0, numColors))
{
throw new ArgumentException(
$"Graph cannot be colored with {numColors} color(s). " +
$"A larger number of colors may be required.");View on GitHub (pinned to 96e2905cab)