Backtracking algorithm