BackTracking Algorithms

Slides:



Advertisements
Similar presentations
110/6/2014CSE Suprakash Datta datta[at]cse.yorku.ca CSE 3101: Introduction to the Design and Analysis of Algorithms.
Advertisements

Traveling Salesperson Problem
Types of Algorithms.
1.1 Data Structure and Algorithm Lecture 6 Greedy Algorithm Topics Reference: Introduction to Algorithm by Cormen Chapter 17: Greedy Algorithm.
Greed is good. (Some of the time)
Techniques for Dealing with Hard Problems Backtrack: –Systematically enumerates all potential solutions by continually trying to extend a partial solution.
October 1, 2012Introduction to Artificial Intelligence Lecture 8: Search in State Spaces II 1 A General Backtracking Algorithm Let us say that we can formulate.
Branch & Bound Algorithms
B ACKTRACK SEARCH ALGORITHM. B ACKTRACKING Suppose you have to make a series of decisions, among various choices, where You don’t have enough information.
15-May-15 Dynamic Programming. 2 Algorithm types Algorithm types we will consider include: Simple recursive algorithms Backtracking algorithms Divide.
Sum of Subsets and Knapsack
November 10, 2009Introduction to Cognitive Science Lecture 17: Game-Playing Algorithms 1 Decision Trees Many classes of problems can be formalized as search.
Constraint Satisfaction Problems
Spring 2010CS 2251 Graphs Chapter 10. Spring 2010CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs.
24-Jun-15 Pruning. 2 Exponential growth How many leaves are there in a complete binary tree of depth N? This is easy to demonstrate: Count “going left”
Ch 13 – Backtracking + Branch-and-Bound
Module #1 - Logic 1 Based on Rosen, Discrete Mathematics & Its Applications. Prepared by (c) , Michael P. Frank and Modified By Mingwu Chen Trees.
Backtracking.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
Busby, Dodge, Fleming, and Negrusa. Backtracking Algorithm Is used to solve problems for which a sequence of objects is to be selected from a set such.
Dr. Jouhaina Chaouachi Siala
Artificial Intelligence Lecture 9. Outline Search in State Space State Space Graphs Decision Trees Backtracking in Decision Trees.
Difficult Problems. Polynomial-time algorithms A polynomial-time algorithm is an algorithm whose running time is O(f(n)), where f(n) is a polynomial A.
Backtracking. N-Queens The object is to place queens on a chess board in such a way as no queen can capture another one in a single move –Recall that.
Lecture 5: Backtracking Depth-First Search N-Queens Problem Hamiltonian Circuits.
HISTORY The problem was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss have worked.
BackTracking CS335. N-Queens The object is to place queens on a chess board in such as way as no queen can capture another one in a single move –Recall.
Dr.Abeer Mahmoud ARTIFICIAL INTELLIGENCE (CS 461D) Dr. Abeer Mahmoud Computer science Department Princess Nora University Faculty of Computer & Information.
1 Spanning Trees Longin Jan Latecki Temple University based on slides by David Matuszek, UPenn, Rose Hoberman, CMU, Bing Liu, U. of Illinois, Boting Yang,
Contents of Chapter 7 Chapter 7 Backtracking 7.1 The General method
CS 312: Algorithm Analysis Lecture #32: Intro. to State-Space Search This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported.
State-Space Searches. 2 State spaces A state space consists of A (possibly infinite) set of states The start state represents the initial problem Each.
Discrete Structures Lecture 12: Trees Ji Yanyan United International College Thanks to Professor Michael Hvidsten.
Trees – Chapter 9 Slides courtesy of Dr. Michael P. Frank University of Florida Dept. of Computer & Information Science & Engineering.
CSE 589 Part VI. Reading Skiena, Sections 5.5 and 6.8 CLR, chapter 37.
Agenda Review: –Planar Graphs Lecture Content:  Concepts of Trees  Spanning Trees  Binary Trees Exercise.
Algorithms April-May 2013 Dr. Youn-Hee Han The Project for the Establishing the Korea ㅡ Vietnam College of Technology in Bac Giang.
Graphs A ‘Graph’ is a diagram that shows how things are connected together. It makes no attempt to draw actual paths or routes and scale is generally inconsequential.
Types of Algorithms. 2 Algorithm classification Algorithms that use a similar problem-solving approach can be grouped together We’ll talk about a classification.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Search in State Spaces Problem solving as search Search consists of –state space –operators –start state –goal states A Search Tree is an efficient way.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
Analysis & Design of Algorithms (CSCE 321)
Chapter 13 Backtracking Introduction The 3-coloring problem
February 11, 2016Introduction to Artificial Intelligence Lecture 6: Search in State Spaces II 1 State-Space Graphs There are various methods for searching.
Backtracking. 2 Suppose you have to make a series of decisions, among various choices, where You don’t have enough information to know what to choose.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
CSG3F3/ Desain dan Analisis Algoritma
Backtracking.
BackTracking CS255.
Depth-First Search N-Queens Problem Hamiltonian Circuits
Discrete Mathematicsq
Data Structures and Algorithms
Design and Analysis of Algorithm
Artificial Intelligence Problem solving by searching CSC 361
Types of Algorithms.
Spanning Trees Longin Jan Latecki Temple University based on slides by
Back Tracking.
Types of Algorithms.
A General Backtracking Algorithm
Haskell Tips You can turn any function that takes two inputs into an infix operator: mod 7 3 is the same as 7 `mod` 3 takeWhile returns all initial.
Backtracking.
Pruning 24-Feb-19.
Backtracking.
Backtracking and Branch-and-Bound
Types of Algorithms.
Spanning Trees Longin Jan Latecki Temple University based on slides by
Lecture 4: Tree Search Strategies
Backtracking.
Presentation transcript:

BackTracking Algorithms Briana B. Morrison With thanks to Dr. Hung

Topics What is Backtracking N-Queens Problem Sum of Subsets Graph Coloring Hamiltonian Circuits Other Problems

Algorithm Design Result Human Problems Input Data Structures Processing Output Data Structures Computer Algorithms

Algorithm Design … For a problem? What is an Optimal Solution? Minimum CPU time Minimum memory Example: Given 4 numbers, sort it to nonincreasing order. Method 1: Sequential comparison 1. Find the largest (3 comparisons) 2. Find the second largest (2 comparisons) 3. Find the third largest (1 comparisons) 4. Find the fourth largest A total of 6 comparisons

Algorithm Design … For a problem? What is an Optimal Solution? Minimum CPU time Minimum memory Example: Given 4 numbers, sort it to nonincreasing order. Method 2: Somewhat clever method a2 a3 a1 a2 a3 a4 (4 comparisons) a3 a2 a4 (5 comparisons) a2 a3 a1 a3 a4 a2 a3 or a1

Backtracking Problems Find your way through the well-known maze of hedges by Hampton Court Palace in England? Until you reached a dead end. 0-1 Knapsack problem – exponential time complexity. N-Queens problem.

Backtracking Suppose you have to make a series of decisions, among various choices, where You don’t have enough information to know what to choose Each decision leads to a new set of choices Some sequence of choices (possibly more than one) may be a solution to your problem Backtracking is a methodical way of trying out various sequences of decisions, until you find one that “works”

Introduction Backtracking is used to solve problems in which a sequence of objects is chosen from a specified set so that the sequence satisfies some criterion. Backtracking is a modified depth-first search of a tree. Backtracking involves only a tree search. Backtracking is the procedure whereby, after determining that a node can lead to nothing but dead nodes, we go back (“backtrack”) to the node’s parent and proceed with the search on the next child.

Introduction … We call a node nonpromising if when visiting the node we determine that it cannot possibly lead to a solution. Otherwise, we call it promising. In summary, backtracking consists of Doing a depth-first search of a state space tree, Checking whether each node is promising, and, if it is nonpromising, backtracking to the node’s parent. This is called pruning the state space tree, and the subtree consisting of the visited nodes is called the pruned state space tree.

Solving a maze Given a maze, find a path from start to finish At each intersection, you have to decide between three or fewer choices: Go straight Go left Go right You don’t have enough information to choose correctly Each choice leads to another set of choices One or more sequences of choices may (or may not) lead to a solution Many types of maze problem can be solved with backtracking

Coloring a map You wish to color a map with not more than four colors red, yellow, green, blue Adjacent countries must be in different colors You don’t have enough information to choose colors Each choice leads to another set of choices One or more sequences of choices may (or may not) lead to a solution Many coloring problems can be solved with backtracking

Solving a puzzle In this puzzle, all holes but one are filled with white pegs You can jump over one peg with another Jumped pegs are removed The object is to remove all but the last peg You don’t have enough information to jump correctly Each choice leads to another set of choices One or more sequences of choices may (or may not) lead to a solution Many kinds of puzzle can be solved with backtracking

Backtracking (animation) ? dead end dead end dead end ? start ? ? dead end dead end ? success!

N-Queens Problem Try to place N queens on an N * N board such that none of the queens can attack another queen. Remember that queens can move horizontally, vertically, or diagonally any distance. Let’s consider the 8 queen example…

The 8-Queens Example

Let’s look at it run

Terminology I A tree is composed of nodes There are three kinds of nodes: The (one) root node Internal nodes Backtracking can be thought of as searching a tree for a particular “goal” leaf node Leaf nodes

Terminology II Each non-leaf node in a tree is a parent of one or more other nodes (its children) Each node in the tree, other than the root, has exactly one parent parent children Usually, however, we draw our trees downward, with the root at the top parent children

Real and virtual trees There is a type of data structure called a tree But we are not using it here If we diagram the sequence of choices we make, the diagram looks like a tree In fact, we did just this a couple of slides ago Our backtracking algorithm “sweeps out a tree” in “problem space”

The backtracking algorithm Backtracking is really quite simple--we “explore” each node, as follows: To “explore” node N: 1. If N is a goal node, return “success” 2. If N is a leaf node, return “failure” 3. For each child C of N, 3.1. Explore C 3.1.1. If C was successful, return “success” 4. Return “failure”

Sum-of-Subsets problem Recall the thief and the 0-1 Knapsack problem. The goal is to maximize the total value of the stolen items while not making the total weight exceed W. If we sort the weights in nondecreasing order before doing the search, there is an obvious sign telling us that a node is nonpromising.

Sum-of-Subsets problem … Let total be the total weight of the remaining weights, a node at the ith level is nonpromising if weight + total > W

Example Say that our weight values are 5, 3, 2, 4, 1 W is 8 We could have 5 + 3 5 + 2 + 1 4 + 3 + 1 We want to find a sequence of values that satisfies the criteria of adding up to W

Tree Space Visualize a tree in which the children of the root indicate whether or not value has been picked (left is picked, right is not picked) Sort the values in non-decreasing order so the lightest value left is next on list Weight is the sum of the weights that have been included at level i Let weight be the sum of the weights that have been included up to a node at level i. Then, a node at the ith level is nonpromising if weight + wi+1 > W

Sum-of-Subsets problem … Example: Show the pruned state space tree when backtracking is used with n = 4, W = 13, and w1 = 3, w2 = 4, w3 = 5, and w4 = 6. Identify those nonpromising nodes.

Full example: Map coloring The Four Color Theorem states that any map on a plane can be colored with no more than four colors, so that no two countries with a common border are the same color For most maps, finding a legal coloring is easy For some maps, it can be fairly difficult to find a legal coloring We will develop a complete Java program to solve this problem

Data structures We need a data structure that is easy to work with, and supports: Setting a color for each country For each country, finding all adjacent countries We can do this with two arrays An array of “colors”, where countryColor[i] is the color of the ith country A ragged array of adjacent countries, where map[i][j] is the jth country adjacent to country i Example: map[5][3]==8 means the 3th country adjacent to country 5 is country 8

Creating the map 1 4 2 3 6 5 int map[][]; void createMap() { map = new int[7][]; map[0] = new int[] { 1, 4, 2, 5 }; map[1] = new int[] { 0, 4, 6, 5 }; map[2] = new int[] { 0, 4, 3, 6, 5 }; map[3] = new int[] { 2, 4, 6 }; map[4] = new int[] { 0, 1, 6, 3, 2 }; map[5] = new int[] { 2, 6, 1, 0 }; map[6] = new int[] { 2, 3, 4, 1, 5 }; }

Setting the initial colors static final int NONE = 0; static final int RED = 1; static final int YELLOW = 2; static final int GREEN = 3; static final int BLUE = 4; int mapColors[] = { NONE, NONE, NONE, NONE, NONE, NONE, NONE };

The main program (The name of the enclosing class is ColoredMap) public static void main(String args[]) { ColoredMap m = new ColoredMap(); m.createMap(); boolean result = m.explore(0, RED); System.out.println(result); m.printMap(); }

The backtracking method boolean explore(int country, int color) { if (country >= map.length) return true; if (okToColor(country, color)) { mapColors[country] = color; for (int i = RED; i <= BLUE; i++) { if (explore(country + 1, i)) return true; } return false;

Checking if a color can be used boolean okToColor(int country, int color) { for (int i = 0; i < map[country].length; i++) { int ithAdjCountry = map[country][i]; if (mapColors[ithAdjCountry] == color) { return false; } return true;

Printing the results void printMap() { for (int i = 0; i < mapColors.length; i++) { System.out.print("map[" + i + "] is "); switch (mapColors[i]) { case NONE: System.out.println("none"); break; case RED: System.out.println("red"); break; case YELLOW: System.out.println("yellow"); break; case GREEN: System.out.println("green"); break; case BLUE: System.out.println("blue"); break; } } }

Recap We went through all the countries recursively, starting with country zero At each country we had to decide a color It had to be different from all adjacent countries If we could not find a legal color, we reported failure If we could find a color, we used it and recurred with the next country If we ran out of countries (colored them all), we reported success When we returned from the topmost call, we were done

Hamiltonian Circuits Problem Hamiltonian circuit (tour) of a graph is a path that starts at a given vertex, visits each vertex in the graph exactly once, and ends at the starting vertex.

State Space Tree Put the starting vertex at level 0 in the tree At level 1, create a child node for the root node for each remaining vertex that is adjacent to the first vertex. At each node in level 2, create a child node for each of the adjacent vertices that are not in the path from the root to this vertex, and so on.

Example

x x Backtracking Algorithms How can a computer play the game? Remember Deep Blue? The tic-tac-toe game

Backtracking Algorithms 0 1 2 x (0,0)H (0,1)H (0,2)H (1,0)H... 1 (0,0)C, (0,1)C, (1,0)C... x 2 (0,1)H, (1,0)H, …, (2,2)H x (0,1)C, (1,0)C, (1,2)C, (2,0)C... : Computer : Human The tic-tac-toe game

Backtracking Algorithms 3 missionaries and 2 cannibals want to cross the river Condition: 1. A boat can take one or two (must include a missionary) 2. At any time, on either bank, the number of missionaries must not be less than the number of cannibals.

Backtracking Search Essentially a simplified depth-first algorithm using recursion

Backtracking Search (3 variables) Assignment = {}

Backtracking Search (3 variables) X1 v11 Assignment = {(X1,v11)}

Backtracking Search (3 variables) X1 v11 X3 v31 Assignment = {(X1,v11), (X3,v31)}

Backtracking Search (3 variables) X1 v11 Then, the search algorithm backtracks to the previous variable and tries another value X3 v31 X2 Assume that no value of X2 leads to a valid assignment Assignment = {(X1,v11), (X3,v31)}

Backtracking Search (3 variables) X1 v11 X3 v31 v32 X2 Assignment = {(X1,v11), (X3,v32)}

Backtracking Search (3 variables) The search algorithm backtracks to the previous variable (X3) and tries another value. But assume that X3 has only two possible values. The algorithm backtracks to X1 X1 v11 X3 v31 v32 X2 X2 Assume again that no value of X2 leads to a valid assignment Assignment = {(X1,v11), (X3,v32)}

Backtracking Search (3 variables) X1 v11 v12 X3 v31 v32 X2 X2 Assignment = {(X1,v12)}

Backtracking Search (3 variables) X1 v11 v12 X3 X2 v31 v32 v21 X2 X2 Assignment = {(X1,v12), (X2,v21)}

Backtracking Search (3 variables) X1 v11 v12 X3 X2 The algorithm need not consider the variables in the same order in this sub-tree as in the other v31 v32 v21 X2 X2 Assignment = {(X1,v12), (X2,v21)}

Backtracking Search (3 variables) X1 v11 v12 X3 X2 v31 v32 v21 X2 X2 X3 v32 Assignment = {(X1,v12), (X2,v21), (X3,v32)}

Backtracking Search (3 variables) X1 v11 v12 X3 X2 v31 v32 v21 The algorithm need not consider the values of X3 in the same order in this sub-tree X2 X2 X3 v32 Assignment = {(X1,v12), (X2,v21), (X3,v32)}

Backtracking Search (3 variables) X1 v11 v12 X3 X2 v31 v32 v21 Since there are only three variables, the assignment is complete X2 X2 X3 v32 Assignment = {(X1,v12), (X2,v21), (X3,v32)}

Backtracking Algorithm [This recursive algorithm keeps too much data in memory. An iterative version could save memory (left as an exercise)] Backtracking Algorithm CSP-BACKTRACKING(A) If assignment A is complete then return A X  select a variable not in A D  select an ordering on the domain of X For each value v in D do Add (Xv) to A If A is valid then result  CSP-BACKTRACKING(A) If result  failure then return result Return failure Call CSP-BACKTRACKING({})

Map Coloring {} WA=red WA=green WA=blue NT=green NT=blue Q=red Q=blue SA Q NSW V T

Chapter Summary Backtracking is an algorithm design technique for solving problems in which the number of choices grows at least exponentially with their instant size. This approach makes it possible to solve many large instances of NP-hard problems in an acceptable amount of time. The technique constructs a pruned state space tree. Backtracking constructs its state-space tree in the depth-first search fashion in the majority of its applications.