Skip to content

Commit fdb271e

Browse files
authored
Update backtracking.md
1 parent fbc8fe0 commit fdb271e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

notes/backtracking.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,49 @@ Main Idea:
209209
6. If the partial solution is complete and valid, record or output it.
210210
7. If all options are exhausted at a level, remove the last component and backtrack to the previous level.
211211

212+
General Template (pseudocode)
213+
214+
```
215+
function backtrack(partial):
216+
if is_complete(partial):
217+
handle_solution(partial)
218+
return // or continue if looking for all solutions
219+
220+
for candidate in generate_candidates(partial):
221+
if is_valid(candidate, partial):
222+
place(candidate, partial) // extend partial with candidate
223+
backtrack(partial)
224+
unplace(candidate, partial) // undo extension (backtrack)
225+
```
226+
227+
Pieces you supply per problem:
228+
229+
* `is_complete`: does `partial` represent a full solution?
230+
* `handle_solution`: record/output the solution.
231+
* `generate_candidates`: possible next choices given current partial.
232+
* `is_valid`: pruning test to reject infeasible choices early.
233+
* `place` / `unplace`: apply and revert the choice.
234+
235+
Python-ish Generic Framework
236+
237+
```python
238+
def backtrack(partial, is_complete, generate_candidates, is_valid, handle_solution):
239+
if is_complete(partial):
240+
handle_solution(partial)
241+
return
242+
243+
for candidate in generate_candidates(partial):
244+
if not is_valid(candidate, partial):
245+
continue
246+
# make move
247+
partial.append(candidate)
248+
backtrack(partial, is_complete, generate_candidates, is_valid, handle_solution)
249+
# undo move
250+
partial.pop()
251+
```
252+
253+
You can wrap those callbacks into a class or closures for stateful problems.
254+
212255
#### N-Queens Problem
213256

214257
The N-Queens problem is a classic puzzle in which the goal is to place $N$ queens on an $N \times N$ chessboard such that no two queens threaten each other. In chess, a queen can move any number of squares along a row, column, or diagonal. Therefore, no two queens can share the same row, column, or diagonal.

0 commit comments

Comments
 (0)