Chapter 2 - Implicit Tree and Backtracking
We can also treat lists as a tree!
Permal Algorithm
In CS310 we are familiar with the permal algorithm, in reality, this is just backtracking. Backtracking is the idea that we can diverge lists to a tree, and if something doesn't work out we can end the path of the tree and try the other path of the tree.
global Buffer[1..n];
procedure PermDriver(n;;);
output: Prints all n! permutations of 1 through n;
for i ← 1 to n do Buffer[i] ← i endfor; { initializes Buffer[1..n] }
Permall(n)
end_PermDriver;
global n; { just to keep the parameter list less cluttered }
procedure Permall(h;;); { h = tree_height of current vertex }
local i; { remember which child to process next in each iteration }
if h equals zero then print Buffer[1..n] endif;
for i ← 1 to h do { simulates: foreach child i of the current vertex at this height do }
swap Buffer values in location h and location i;
Permall(h - 1); { recurse }
swap Buffer values in location h and location i
endfor { <- this swap is proven to restore Buffer perfectly by induction starting with height 1. }
end_Permall;
Applications of Permall (Backtracking)
Last updated