Backtracking

Published by

on

Backtracking is a method that removes child nodes that will not satisfy the condition and go back to parent node to proceed to other child nodes. Usually backtracking is related with DFS, which searches through all the children nodes.

Typically, problems that require “Print all” or “Get all” are the ones that need backtracking technique to solve.

Pseudo code

1. Recursive backtracking solution

void solve(n, other params) : 
    if (found a solution) :
        solutionsFound = solutionsFound + 1;
        displaySolution();
        if (solutionsFound >= solutionTarget) : 
            System.exit(0);
        return;

    for (val = first to last) :
        if (isValid(val, n)) :
            applyValue(val, n);
            solve(n+1, other params); // other params should include the result of applyValue()
            removeValue(val, n);

if we don’t allow using the same node multiple times, iteration should start from the passed index

void solve(n, other params, idx) :
    if (found a solution) :
        solutionsFound = solutionsFound + 1;
        displaySolution();
        if (solutionsFound >= solutionTarget) : 
            System.exit(0);
        return

    for (val = idx to last) :
        if (isValid(val, n)) :
            applyValue(val, n);
            solve(n+1, other params, idx+1); // other params should include the result of applyValue()
            removeValue(val, n);

2. Finding whether solution exists or not

boolean solve(n, other params) :
    if (found a solution) :
        displaySolution();
        return true;

    for (val = first to last) :
        if (isValid(val, n)) :
            applyValue(val, n);
            if (solve(n+1, other params)) // other params should include the result of applyValue()
                return true;
            removeValue(val, n);
        return false;

Exercises

Reference

One response to “Backtracking”

  1. […] 의 경우 백트래킹의 수도코드처럼 isValid 할 경우만 recursion 돌리면 […]

    Like

Leave a comment

Previous Post
Next Post