TheAlgorithms/Java · error · IllegalArgumentException

Source and sink must be valid vertex indices

Error message

Source and sink must be valid vertex indices

What it means

PushRelabel.validate throws this IllegalArgumentException when source or sink is outside [0, n). It is the final guard in validate, ensuring indices are safe before the algorithm accesses height, excess, and capacity arrays.

Source

Thrown at src/main/java/com/thealgorithms/graph/PushRelabel.java:159

    }

    private static void validate(int[][] capacity, int source, int sink) {
        if (capacity == null || capacity.length == 0) {
            throw new IllegalArgumentException("Capacity matrix must not be null or empty");
        }
        int n = capacity.length;
        for (int i = 0; i < n; i++) {
            if (capacity[i] == null || capacity[i].length != n) {
                throw new IllegalArgumentException("Capacity matrix must be square");
            }
            for (int j = 0; j < n; j++) {
                if (capacity[i][j] < 0) {
                    throw new IllegalArgumentException("Capacities must be non-negative");
                }
            }
        }
        if (source < 0 || sink < 0 || source >= n || sink >= n) {
            throw new IllegalArgumentException("Source and sink must be valid vertex indices");
        }
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Verify source and sink are in [0, n - 1] before calling.
  2. Convert 1-based external labels to 0-based.
  3. Ensure the matrix dimension matches the true vertex count.

Example fix

// before
int flow = PushRelabel.maxFlow(cap, 1, numVertices);

// after
int flow = PushRelabel.maxFlow(cap, 0, numVertices - 1);
Defensive patterns

Strategy: validation

Validate before calling

int n = capacity.length;
if (source < 0 || sink < 0 || source >= n || sink >= n) {
    throw new IllegalArgumentException("Invalid source/sink");
}

Prevention

When it happens

Trigger: Calling PushRelabel.maxFlow with source or sink negative or >= capacity.length.

Common situations: 1-based labels passed directly. Vertex count mismatch. Sink set to numVertices instead of numVertices - 1.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/b3715a0fc9f28fd3. Report an issue: GitHub.