Backtracking
General algorithm bool finished = FALSE; backtrack(int a[], int k, data input){ int c[MAXCANDIDATES],ncandidates,i; if (is_a_solution(a,k,input) process_solution(a,k,input); else { k = k+1; construct_candidates(a,k,input,c,&ncandidates); for (i=0; i<ncandidates;i++){ a[k] = c[i]; backtrack(a,k,input); if (finished ) return; }
Pruning Process of not considering cases because they cannot be solutions. Very problem specific.
Graph Traversals
Graph flavors Undirected vs directed Weighted vs unweighted Cyclic vs acyclic Simple vs non-simple (self-loops, multi-edges) Embedded vs topological Implicit vs explicit Labeled vs unlabeled
Data Structures for Graphs Adjacency matrix List of adjacency lists Array/vector of adjacency lists List or table of edges.
Graph traversals, basic algorithm: traverse_graph(graph g, node start){ Structure s; Node v; Node visited[]=false; add(s,start); While ( !empty s){ v=get1(s) If ! visited[v] { visit(v) visited[v] = true; foreach x=neighbor(v) add(s,x) }
Finding cycles Dfs a discovery is a cycle.
Algorithm for Topological sort Ideal data structure: array/vector of adjacency lists. vector pred_count[]=0; Step 1: Go through each adjacency list, and add one to the the pred_count entry of the node listed. Repeat until none found: Go through pred_count vector until a node with 0 predecessors is found; output it, subtract 1 from each of its neighbors. If there are nodes left to output, there is a cycle and no topological sort possible, ow. We are done.
More graph algorithms
Some more concepts Degree of a node: number of edges it “touches” Indegree: edges pointed to it; Outdegree: edges pointed from it. Note that the sum of the degree = |edges| *2 Therefore, nodes with odd degree is even. Graphs which “can be drawn without lifting the pen from the paper” have at most two nodes of odd degree. Also indegrees = outdegrees.
Even more concepts Trees: Undirected graphs without cycles. Rooted trees: Direted graphs where oevery node but 1 has indegree 1 Binary tree: