Working recursive backtracking algorithm.