DEV Community

drevispas
drevispas

Posted on

1 1

Programming Template: BackTraking

This is a simple code example of backtraking. This traverses the problem space in depth-first order. I memorized it as a solution template.

const int MAXC = 4;
int finished = 0;
void bt(int a[], int k, int n) {
    int candidates[MAXC], numCand, i;
    if (solved(a, k, n)) {
        answer(a, k, n);
        return;
    }
    numCand = getCandidates(a, k, n, candidates);
    for (i = 0; i < numCand; i++) {
        a[k] = candidates[i];
        bt(a, k + 1, n);
        if (finished) return;
    }
}

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay