Scientific Programming. Backtracking

Size: px
Start display at page:

Download "Scientific Programming. Backtracking"

Transcription

1 Scientific Programming Backtracking Alberto Montresor Università di Trento 2018/12/15 This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

2 Table of contents 1 Introduction 2 Enumeration Subsets Permutations Games

3 Introduction Introduction Problem classes (decisional, search, optimization) Definition bases on the concept of admissible solution: a solution that satisfies a given set of criteria Typical problems Build one or all admissible solution Counting the admissible solutions Find the admissible solution "largest", "smallest", in general "optimal" Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 1 / 37

4 Introduction Typical problems Enumeration List algorithmically all possible solutions (search space) Example: list all the permutations of a set Build at least a solution We use the algorithm for enumeration, stopping at the first solution found Example: identify a sequence of steps in the Fifteen game Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 2 / 37

5 Introduction Typical problems Count the solutions In some cases, it is possible to count in analytical way Example: counting the number of subsets of k elements taken by a set of n elements n! k! (n k)! In other cases, we build the solutions and we count them Example: number of subsets of a integer set S whose sum is equal to a prime number Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 3 / 37

6 Introduction Typical problems Find optimal solutions We enumerate all possible solutions and evaluate them through a cost function Only if other techniques are not possible: Dynamic programming Greedy Example: Hamiltonian circuit (Traveling salesman) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 4 / 37

7 Introduction Build all solutions To build all the solutions, we use a "brute-force" approach Sometimes, it is the only possible way The power of modern computer makes possible to deal with problems medium-small problems 10! = (permutation of 10 elements) 2 20 = (subsets of 20 elements) Sometimes, the space of all possible solutions does not need to be analyzed entirely Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 5 / 37

8 Introduction Backtracking Approach "Prova a fare qualcosa, e se non va bene, disfalo e prova qualcos altro" "Ritenta, e sarai più fortunato" How it works? A systematic methods to iterate all possible instances of a research space It is an algorithm technique that, as the others, need to be "customized" for the specific problem to be solved. Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 6 / 37

9 Introduction General organization General organization A solution is represented by a list S The content of element S[i] is taken from a set of choices C that depends on the problem Examples C generic set, possible solutions permutations of C C generic set, possible solutions subsets of C C game moves, possible solutions a sequence of moves C edges of a graph, possible solutions paths Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 7 / 37

10 Introduction Partial solutions At each step, we start from a partial solution S where k 0 choices have been already taken If S[0 : k] is an admissible solution, we "process" it E.g., we can print it We can then decide to stop here or keep going by listing/printing all solutions If S[0 : k] is not a complete solution: If possible, we extended solution S[0 : k] with one of the possible choices to get a solution S[0 : k + 1] Otherwise, we "cancel" the element S[k] (backtrack) and we go back to to solution S[0 : k 1] Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 8 / 37

11 Introduction Decision trees Decision tree Search space Root Empty solution Internal nodes Partial solutions Leaves Admissible solutions S[0] S[1] S[2] S[3] S[3] Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 9 / 37

12 Introduction Pruning "Branches" of the trees that do not bring to admissible solutions can be "pruned" The evaluation is done in the partial solutions corresponding to internal nodes Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 10 / 37

13 Enumeration boolean enumeration(object[ ] S, int n, int i,... ) Set C = choices(s, n, i,...) % Compute C based on S[0 : i 1] foreach c C do S[i] = c if isadmissible(s, n, i) then if processsolution(s, n, i,...) then return True if enumeration(s, n, i + 1,...) then return True return False Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 11 / 37

14 Enumeration S: list containing the partial solutions i: current index...: additional information C: the set of possible candidates to extend the current solution isadmissible(): returns True if S[0 : i] is an admissible solution processsolution(): returns True to stop the execution at the first admissible solution False to explore the entire tree Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 12 / 37

15 Subsets Example 1 List all subsets of {0,..., n 1} def subsets(s,n,i): C = [1, 0] if i<n else [] for c in C: S[i] = c if i==n-1: if (processsolution(s)): return True else: subsets(s,n,i+1) return False def processsolution(s): for i in range(len(s)): if (S[i]==1): print(i, "", end="") print("") return False n = 4 S = [0]*n subsets(s,4,0) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 13 / 37

16 Subsets Example 1 (Clean-up version) List all possible subsets of {0,..., n 1} def subsets(s,n,i): for c in [1, 0]: S[i] = c if i == n-1: processsolution(s) else: subsets(s,n,i+1) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 14 / 37

17 Subsets Example 1 There is no pruning. All the possible space is explored. But this is required by the definition of the problem Computational complexity O(n2 n ) In which order sets are printed? Is it possible to think to an iterative version, ad-hoc for this problem? (non-backtracking) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 15 / 37

18 Subsets Example 1 subsets(int n) for j = 0 to 2 n 1 do print { for i = 0 to n 1 do if (j and 2 i ) 0 then print i print } Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 16 / 37

19 Subsets Example 2 List all possible subsets of size k of a set {0,..., n 1} Iterative version What is the cost? Solution based on backtracking Can we prune? Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 17 / 37

20 Subsets Example 2 - Attempt 1 def subsets(s, k, n,i): C = [1,0] for c in C: S[i] = c if i == n-1: if admissible(s, k): processsolution(s) else: subsets(s, k, n, i+1): def admissible(s, k): return sum(s) == k def processsolution(s): for i in range(len(s)): if (S[i]==1): print(i, "", end="") print("") return False n = 4 k = 2 S = [0]*n subsets(s, 2, 4, 0) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 18 / 37

21 Subsets Example 2 - Attempt 2 def subsets(s, k, n, i, count): C = [1, 0] for c in C: S[i] = c count = count + c if i == n-1: if count == k: processsolution(s) else: subsets(s,k, n, i+1, count) count = count - c def admissible(s, k): tot = sum(s) return tot == k def processsolution(s): for i in range(len(s)): if (S[i]==1): print(i, "", end="") print("") return False n = 4 k = 2 S = [0]*n subsets(s, 2, 4, 0, 0) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 19 / 37

22 Subsets Example 2 - Attempt 3 def subsets(s, k, n, i, count): if count < k and count + (n-i) >= k: C = [1,0] else C = [] for c in C: S[i] = c count = count + c if count == k: processsolution(s) else: subsets(s, k, n, i+1, count) count = count - c S[i] = 0 def processsolution(s): for i in range(len(s)): if (S[i]==1): print(i, "", end="") print("") return False n = 4 k = 2 S = [0]*n subsets(s, 2, 4, 0, 0) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 20 / 37

23 Subsets Example Esempio 2: vantaggi 2: advantages Alberto Montresor Montresor (UniTN) SP - Backtracking 2018/12/15 21 / 3720

24 Subsets Example 2 - Summary Cosa abbiamo imparato? By "customizing" the generic algorithm, we can get a more efficient solution It is efficient for small values of k (close to 1) large values of k (close to n) No great saving for n/2 It is difficult to obtain the same efficiency with an iterative algorithm Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 22 / 37

25 Permutations Example 3 Print all permutations of a set A def permutations(s, i, original): for c in original: S[i] = c original.remove(c) if (len(original)==0): print(s) else: permutations(s, i+1, original) original.add(c) original = { 1,2,3,4 } S = [0]*len(original) permutations(s, 0, original) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 23 / 37

26 Games Eight queens puzzle Problem The eight queens puzzle is the problem of placing eight chess queens on an 8 8 chessboard so that no two queens threaten each other History: Introduced by Max Bezzel (1848) Gauss found 72 of the 92 solutions Let s start from the stupidest approach, and let s refine the solution step by step Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 24 / 37

27 Games Eight queens puzzle Idea: There are n 2 possible positions where a queen may be located S[0 : n 2 ] binary array S[i] = True "queen in i" isadmissible() i == n 2 choices(s, n, i) pruning {True, False} # Solutions for n = Comments if the new queen threaten one of the existing queens, returns Maybe we have a representation problem? Binary matrix, really sparse Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 25 / 37

28 Games Better, but the space is still huge... Problem: how to distinguish between a solution " " and a solution " "? Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 26 / 37 Eight queens puzzle Idea: For each queen, there are n 2 possible positions S[0 : n] coordinates in {0... n 2 1} isadmissible() S[i] coordinate of queen i i == n choices(s, n, i) {0... n 2 1} pruning returns the subset of legal moves # Solutions for n = 8 (n 2 ) n = 64 8 = Comments

29 Games Eight queens puzzle Idea: do not place queens in positions that occur "before" the ones already taken S[0 : n] coordinates in {0... n 2 1} isadmissible() S[i] coordinate of queen i i == n choices(s, n, i) {0... n 2 1} pruning returns legal moves, S[i] > S[i 1] # Solutions for n = 8 (n 2 ) n /n! = 2 48 / Comments Very good, but there is still space for improvement Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 27 / 37

30 Games Eight queens puzzle Idea: each row of the board must contain exactly one queen S[0 : n] coordinates in {0... n 1} isadmissible() S[i] column of queen i, where row = i i == n choices(s, n, i) {0... n 1} pruning returns only legal columns # Solutions for n = 8 n n = Comments Almost there Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 28 / 37

31 Games Eight queens puzzle Idea: every column must contain exactly one queen S[0 : n] coordinates in {0... n 1} isadmissible() permutations of {1... n} i == n choices(s, n, i) {0... n 1} pruning removes diagonals # Solutions for n = 8 n! = 8! = Comments Solutions actually visited = Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 29 / 37

32 Games Eight queens puzzle def queens(s, i, columns): for c in columns: S[i] = c columns.remove(c) if (diagonalsok(s,i)): if len(columns)==0: printboard(s) else: queens(s,i+1,columns) columns.add(c) Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 30 / 37

33 lo Knight s tour Enumeration Games Problem A Knight s tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. deri ancora una scacchiera n n; lo scopo è trovare un giro di cavallo, n percorso di mosse valide del cavallo in modo che ogni casella venga al più una volta backtrack Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 31 / 37 30

34 Games Knight s tour Solution Board n n whose cells contains: 0 if the cell has not been visited i if the cell has been visited at step i # Solutions: 64! But: at each step, there are at most 8 possible cells, so the maximum number of visits is In reality, much less thank to pruning Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 32 / 37

35 Games Knight s tour def knight(s, i, x, y): n = len(s) C = moves(s, x, y) if (i == n*n): for k in range(n): print(s[k]) return True else: S[x][y] = i for c in C: if knight(s, i+1, x+dx[c], y+dy[c]): return True S[x][y] = 0 return False Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 33 / 37

36 Games Knight s tour dx = [-1, +1, +2, +2, +1, -1, -2, -2] dy = [-2, -2, -1, +1, +2, +2, +1, -1] def moves(s, x, y): res = set() for i in range(8): nx = x + dx[i] ny = y + dy[i] if (0 <= nx < 8) and (0 <= ny < 8) and S[nx][ny] ==0 : res.add(i) return res Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 34 / 37

37 Games Sudoku - "Suuji wa dokushin ni kagiru" Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 35 / 37

38 Games Sudoku boolean sudoku(int[ ][ ] S, int i) int x = i mod 9 int y = i/9 Set C = Set() if i 80 then if S[x, y] 0 then C.insert(S[x, y]) else for c = 1 to 9 do if check(s, x, y, c) then C.insert(c) int old = S[x, y] foreach c C do S[x, y] = c if i = 80 then processsolution(s, n) return True if sudoku(s, i + 1) then return True S[x, y] = old return False Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 36 / 37

39 Games Sudoku boolean check(int[ ][ ] S, int x, int y, int c) for j = 0 to 8 do if S[x, j] = c then return False if S[j, y] = c then return False int b x = x/3 int b y = y/3 for i x = 0 to 2 do for int i y = 0 to 2 do if S[b x 3 + i x, b y 3 + i y ] = c then return False % Column check % Row check % Subtable check return True Alberto Montresor (UniTN) SP - Backtracking 2018/12/15 37 / 37

Backtracking and Branch-and-Bound

Backtracking and Branch-and-Bound Backtracking and Branch-and-Bound Usually for problems with high complexity Exhaustive Search is too time consuming Cut down on some search using special methods Idea: Construct partial solutions and extend

More information

Chapter-6 Backtracking

Chapter-6 Backtracking Chapter-6 Backtracking 6.1 Background Suppose, if 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

More information

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph COMBINATORIAL SEARCH Algorithms F O U R T H E D I T I O N permutations backtracking counting subsets paths in a graph R O B E R T S E D G E W I C K K E V I N W A Y N E Algorithms, 4 th Edition Robert Sedgewick

More information

Backtracking is a refinement of the brute force approach, which systematically searches for a

Backtracking is a refinement of the brute force approach, which systematically searches for a Backtracking Backtracking is a refinement of the brute force approach, which systematically searches for a solution to a problem among all available options. It does so by assuming that the solutions are

More information

CS 440 Theory of Algorithms /

CS 440 Theory of Algorithms / CS 440 Theory of Algorithms / CS 468 Algorithms in Bioinformaticsi Brute Force. Design and Analysis of Algorithms - Chapter 3 3-0 Brute Force A straightforward approach usually based on problem statement

More information

Combinatorial Search. permutations backtracking counting subsets paths in a graph. Overview

Combinatorial Search. permutations backtracking counting subsets paths in a graph. Overview Overview Exhaustive search. Iterate through all elements of a search space. Combinatorial Search Backtracking. Systematic method for examining feasible solutions to a problem, by systematically eliminating

More information

Coping with the Limitations of Algorithm Power Exact Solution Strategies Backtracking Backtracking : A Scenario

Coping with the Limitations of Algorithm Power Exact Solution Strategies Backtracking Backtracking : A Scenario Coping with the Limitations of Algorithm Power Tackling Difficult Combinatorial Problems There are two principal approaches to tackling difficult combinatorial problems (NP-hard problems): Use a strategy

More information

Backtracking. See Section 7.7 p of Weiss

Backtracking. See Section 7.7 p of Weiss Backtracking See Section 7.7 p 333-336 of Weiss So far we have looked at recursion in general, looked at Dynamic Programming as a way to make redundant recursions less inefficient, and noticed that recursion

More information

Search and Optimization

Search and Optimization Search and Optimization Search, Optimization and Game-Playing The goal is to find one or more optimal or sub-optimal solutions in a given search space. We can either be interested in finding any one solution

More information

Chapter 6 Backtracking Algorithms. Backtracking algorithms Branch-and-bound algorithms

Chapter 6 Backtracking Algorithms. Backtracking algorithms Branch-and-bound algorithms Chapter 6 Backtracking Algorithms Backtracking algorithms Branch-and-bound algorithms 1 Backtracking Algorithm The task is to determine algorithm for finding solutions to specific problems not by following

More information

Backtracking. Examples: Maze problem. The bicycle lock problem: Consider a lock with N switches, each of which can be either 0 or 1.

Backtracking. Examples: Maze problem. The bicycle lock problem: Consider a lock with N switches, each of which can be either 0 or 1. Backtracking Examples: Maze problem Finish Start The bicycle lock problem: Consider a lock with N switches, each of which can be either 0 or 1. We know that the combination that opens the lock should have

More information

Chapter 5 Backtracking 1

Chapter 5 Backtracking 1 Chapter 5 Backtracking 1 The idea A sequence of objects is chosen from a specified set so that the sequence satisfies some criterion Example: n-queens problem Sequence: n positions on the chessboard Set:

More information

Lecture 14: General Problem-Solving Methods

Lecture 14: General Problem-Solving Methods Lecture 14: General Problem-Solving Methods Problem Solving Methods Greedy Method Divide-and-Conquer Backtracking Dynamic Programming Branch-and-Bound Greedy Method The greedy method consists of an iteration

More information

Lecture 3. Brute Force

Lecture 3. Brute Force Lecture 3 Brute Force 1 Lecture Contents 1. Selection Sort and Bubble Sort 2. Sequential Search and Brute-Force String Matching 3. Closest-Pair and Convex-Hull Problems by Brute Force 4. Exhaustive Search

More information

Constraint Satisfaction Problems (CSPs)

Constraint Satisfaction Problems (CSPs) Constraint Satisfaction Problems (CSPs) CPSC 322 CSP 1 Poole & Mackworth textbook: Sections 4.0-4.2 Lecturer: Alan Mackworth September 28, 2012 Problem Type Static Sequential Constraint Satisfaction Logic

More information

The problem: given N, find all solutions of queen sets and return either the number of solutions and/or the patterned boards.

The problem: given N, find all solutions of queen sets and return either the number of solutions and/or the patterned boards. N-ueens Background Problem surfaced in 1848 by chess player Ma Bezzel as 8 queens (regulation board size) Premise is to place N queens on N N board so that they are non-attacking A queen is one of si different

More information

Questions? You are given the complete graph of Facebook. What questions would you ask? (What questions could we hope to answer?)

Questions? You are given the complete graph of Facebook. What questions would you ask? (What questions could we hope to answer?) P vs. NP What now? Attribution These slides were prepared for the New Jersey Governor s School course The Math Behind the Machine taught in the summer of 2011 by Grant Schoenebeck Large parts of these

More information

Lecture 8 Backtracking

Lecture 8 Backtracking Lecture 8 Backtracking Euiseong Seo (euiseong@skku.edu) 1 Backtracking Systematic method to iterate through all the possible configurations of a search space General algorithm/technique which must be customized

More information

UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis

UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis Lecture 11 Class URL: http://vlsicad.ucsd.edu/courses/cse21-s14/ Lecture 11 Notes Goals for this week (Tuesday) Linearity

More information

SEARCH ALGORITHMS NOTES FOR THE ADVANCED ALGORITHM CLASS

SEARCH ALGORITHMS NOTES FOR THE ADVANCED ALGORITHM CLASS SEARCH ALGORITHMS NOTES FOR THE ADVANCED ALGORITHM CLASS GIUSEPPE PERSIANO Contents 1. Model 1 2. Exhaustive Search 2 3. Backtrack 3 3.1. Backtrack for Sudoku 4 3.2. Backtrack for Vertex Cover 4 4. Branch

More information

CS61B Lecture #35. [The Lecture #32 notes covered lectures #33 and #34.] Today: Enumerated types, backtracking searches, game trees.

CS61B Lecture #35. [The Lecture #32 notes covered lectures #33 and #34.] Today: Enumerated types, backtracking searches, game trees. CS61B Lecture #35 [The Lecture #32 notes covered lectures #33 and #34.] Today: Enumerated types, backtracking searches, game trees. Coming Up: Graph Structures: DSIJ, Chapter 12 Last modified: Mon Nov

More information

BackTracking Introduction

BackTracking Introduction Backtracking BackTracking 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. The classic example

More information

Lecture Chapter 6 Recursion as a Problem Solving Technique

Lecture Chapter 6 Recursion as a Problem Solving Technique Lecture Chapter 6 Recursion as a Problem Solving Technique Backtracking 1. Select, i.e., guess, a path of steps that could possibly lead to a solution 2. If the path leads to a dead end then retrace steps

More information

Algorithm Design Techniques (III)

Algorithm Design Techniques (III) Algorithm Design Techniques (III) Minimax. Alpha-Beta Pruning. Search Tree Strategies (backtracking revisited, branch and bound). Local Search. DSA - lecture 10 - T.U.Cluj-Napoca - M. Joldos 1 Tic-Tac-Toe

More information

Backtracking. Chapter 5

Backtracking. Chapter 5 1 Backtracking Chapter 5 2 Objectives Describe the backtrack programming technique Determine when the backtracking technique is an appropriate approach to solving a problem Define a state space tree for

More information

CS 151. Recursion (Review!) Wednesday, September 19, 12

CS 151. Recursion (Review!) Wednesday, September 19, 12 CS 151 Recursion (Review!) 1 Announcements no class on Friday, and no office hours either (Alexa out of town) unfortunately, Alexa will also just be incommunicado, even via email, from Wednesday night

More information

Chapter S:II. II. Search Space Representation

Chapter S:II. II. Search Space Representation Chapter S:II II. Search Space Representation Systematic Search Encoding of Problems State-Space Representation Problem-Reduction Representation Choosing a Representation S:II-1 Search Space Representation

More information

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Recursion. Dr. Jürgen Eckerle FS Recursive Functions Recursion Dr. Jürgen Eckerle FS 2008 Recursive Functions Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own

More information

Perfect square. #include<iostream> using namespace std; int main(){ int a=1; int square; while(true){ } cout<<square<<endl; }

Perfect square. #include<iostream> using namespace std; int main(){ int a=1; int square; while(true){ } cout<<square<<endl; } Lab 3 Kaikai Bian Perfect square #include using namespace std; int main(){ int a=1; int square; while(true){ } cout

More information

5105 BHARATHIDASAN ENGINEERING COLLEGE

5105 BHARATHIDASAN ENGINEERING COLLEGE CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS II CSE/IT /IV SEMESTER UNIT I PART A 1. Design an algorithm to compute the area and circumference of a circle?(dec 2016) 2. Define recurrence relation? (Dec 2016)

More information

Lecture 2: List algorithms using recursion and list comprehensions

Lecture 2: List algorithms using recursion and list comprehensions Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns

More information

Chapter S:I. I. Introduction. Examples for Search Problems Search Problem Abstraction

Chapter S:I. I. Introduction. Examples for Search Problems Search Problem Abstraction Chapter S:I I. Introduction Examples for Search Problems Search Problem Abstraction S:I-1 Introduction STEIN/LETTMANN 1998-2016 Road Map Problem Search for a route from place A to : A S:I-2 Introduction

More information

Constraint (Logic) Programming

Constraint (Logic) Programming Constraint (Logic) Programming Roman Barták Faculty of Mathematics and Physics, Charles University in Prague, Czech Republic bartak@ktiml.mff.cuni.cz Sudoku Combinatorial puzzle, whose goal is to enter

More information

Jalil Boudjadar, Tommy Färnqvist. IDA, Linköping University. 1 Recursive search Exhaustive search Backtracking

Jalil Boudjadar, Tommy Färnqvist. IDA, Linköping University. 1 Recursive search Exhaustive search Backtracking Lecture 16 Recursive search TDDD86: DALP Print version of the lecture Data structures, algorithms and programming paradigms 4 november 2016 Jalil Boudjadar, Tommy Färnqvist. IDA, Linköping University 16.1

More information

Recursion. move(64, 1, 2, 3);

Recursion. move(64, 1, 2, 3); Recursion Divide and conquer. One of the uses that we make of recursion of the form called divide and conquer, which can be defined generally as the method of solving a problem by dividing it into two

More information

6. Algorithm Design Techniques

6. Algorithm Design Techniques 6. Algorithm Design Techniques 6. Algorithm Design Techniques 6.1 Greedy algorithms 6.2 Divide and conquer 6.3 Dynamic Programming 6.4 Randomized Algorithms 6.5 Backtracking Algorithms Malek Mouhoub, CS340

More information

CSE 100: B+ TREE, 2-3 TREE, NP- COMPLETNESS

CSE 100: B+ TREE, 2-3 TREE, NP- COMPLETNESS CSE 100: B+ TREE, 2-3 TREE, NP- COMPLETNESS Analyzing find in B-trees Since the B-tree is perfectly height-balanced, the worst case time cost for find is O(logN) Best case: If every internal node is completely

More information

Artificial Intelligence Constraint Satisfaction Problems

Artificial Intelligence Constraint Satisfaction Problems Artificial Intelligence Constraint Satisfaction Problems Recall Search problems: Find the sequence of actions that leads to the goal. Sequence of actions means a path in the search space. Paths come with

More information

Problem solving paradigms

Problem solving paradigms Problem solving paradigms Bjarki Ágúst Guðmundsson Tómas Ken Magnússon Árangursrík forritun og lausn verkefna School of Computer Science Reykjavík University Today we re going to cover Problem solving

More information

Heuristic Optimisation

Heuristic Optimisation Heuristic Optimisation Part 3: Classification of algorithms. Exhaustive search Sándor Zoltán Németh http://web.mat.bham.ac.uk/s.z.nemeth s.nemeth@bham.ac.uk University of Birmingham S Z Németh (s.nemeth@bham.ac.uk)

More information

PSD1A. DESIGN AND ANALYSIS OF ALGORITHMS Unit : I-V

PSD1A. DESIGN AND ANALYSIS OF ALGORITHMS Unit : I-V PSD1A DESIGN AND ANALYSIS OF ALGORITHMS Unit : I-V UNIT I -- Introduction -- Definition of Algorithm -- Pseudocode conventions -- Recursive algorithms -- Time and space complexity -- Big- o notation --

More information

CSE 417 Branch & Bound (pt 4) Branch & Bound

CSE 417 Branch & Bound (pt 4) Branch & Bound CSE 417 Branch & Bound (pt 4) Branch & Bound Reminders > HW8 due today > HW9 will be posted tomorrow start early program will be slow, so debugging will be slow... Review of previous lectures > Complexity

More information

Scientific Programming. Trees

Scientific Programming. Trees Scientific Programming Trees Alberto Montresor Università di Trento 2018/11/30 This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Table of contents 1 Introduction

More information

Constraint Satisfaction Problems

Constraint Satisfaction Problems Constraint Satisfaction Problems Robert Platt Northeastern University Some images and slides are used from: 1. AIMA What is a CSP? The space of all search problems states and actions are atomic goals are

More information

Administrative. Local Search!

Administrative. Local Search! Administrative Local Search! CS311 David Kauchak Spring 2013 Assignment 2 due Tuesday before class Written problems 2 posted Class participation http://www.youtube.com/watch? v=irhfvdphfzq&list=uucdoqrpqlqkvctckzqa

More information

Functionally Modular. Self-Review Questions

Functionally Modular. Self-Review Questions Functionally Modular 5 Self-Review Questions Self-review 5.1 Which names are local, which are global and which are built-in in the following code fragment? Global names: Built-in names: space_invaders

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

CSC 427: Data Structures and Algorithm Analysis. Fall 2006

CSC 427: Data Structures and Algorithm Analysis. Fall 2006 CSC 427: Data Structures and Algorithm Analysis Fall 2006 Problem-solving approaches divide & conquer greedy backtracking examples: N-queens, Boggle, 2-D gels hw6: Sudoku solver 1 Divide & Conquer RECALL:

More information

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined): 2-D Arrays We define 2-D arrays similar to 1-D arrays, except that we must specify the size of the second dimension. The following is how we can declare a 5x5 int array: int grid[5][5]; Essentially, this

More information

N-Queens problem. Administrative. Local Search

N-Queens problem. Administrative. Local Search Local Search CS151 David Kauchak Fall 2010 http://www.youtube.com/watch?v=4pcl6-mjrnk Some material borrowed from: Sara Owsley Sood and others Administrative N-Queens problem Assign 1 grading Assign 2

More information

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I MCA 312: Design and Analysis of Algorithms [Part I : Medium Answer Type Questions] UNIT I 1) What is an Algorithm? What is the need to study Algorithms? 2) Define: a) Time Efficiency b) Space Efficiency

More information

Algorithms Interview Questions

Algorithms Interview Questions Algorithms Interview Questions 1. Define the concept of an algorithm. An algorithm is any well-defined computational procedure that takes some value (or set of values) as input and produces some value

More information

Introduction III. Graphs. Motivations I. Introduction IV

Introduction III. Graphs. Motivations I. Introduction IV Introduction I Graphs Computer Science & Engineering 235: Discrete Mathematics Christopher M. Bourke cbourke@cse.unl.edu Graph theory was introduced in the 18th century by Leonhard Euler via the Königsberg

More information

Constraint Satisfaction Problems

Constraint Satisfaction Problems Constraint Satisfaction Problems CE417: Introduction to Artificial Intelligence Sharif University of Technology Spring 2013 Soleymani Course material: Artificial Intelligence: A Modern Approach, 3 rd Edition,

More information

Constraint Satisfaction Problems. Constraint Satisfaction Problems. Constraint Satisfaction Problems

Constraint Satisfaction Problems. Constraint Satisfaction Problems. Constraint Satisfaction Problems CSC384: Intro to Artificial Intelligence Backtracking Search I Announcements Many problems can be represented as a search for a vector of feature values. k-features: variables. Each feature has a value.

More information

CLASS: II YEAR / IV SEMESTER CSE CS 6402-DESIGN AND ANALYSIS OF ALGORITHM UNIT I INTRODUCTION

CLASS: II YEAR / IV SEMESTER CSE CS 6402-DESIGN AND ANALYSIS OF ALGORITHM UNIT I INTRODUCTION CLASS: II YEAR / IV SEMESTER CSE CS 6402-DESIGN AND ANALYSIS OF ALGORITHM UNIT I INTRODUCTION 1. What is performance measurement? 2. What is an algorithm? 3. How the algorithm is good? 4. What are the

More information

Basic Search Algorithms

Basic Search Algorithms Basic Search Algorithms Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Abstract The complexities of various search algorithms are considered in terms of time, space, and cost

More information

Introduction to Algorithms: Brute-Force Algorithms

Introduction to Algorithms: Brute-Force Algorithms Introduction to Algorithms: Brute-Force Algorithms Introduction to Algorithms Brute Force Powering a Number Selection Sort Exhaustive Search 0/1 Knapsack Problem Assignment Problem CS 421 - Analysis of

More information

Computer Science 385 Design and Analysis of Algorithms Siena College Spring Topic Notes: Brute-Force Algorithms

Computer Science 385 Design and Analysis of Algorithms Siena College Spring Topic Notes: Brute-Force Algorithms Computer Science 385 Design and Analysis of Algorithms Siena College Spring 2019 Topic Notes: Brute-Force Algorithms Our first category of algorithms are called brute-force algorithms. Levitin defines

More information

Chapter 10 Part 1: Reduction

Chapter 10 Part 1: Reduction //06 Polynomial-Time Reduction Suppose we could solve Y in polynomial-time. What else could we solve in polynomial time? don't confuse with reduces from Chapter 0 Part : Reduction Reduction. Problem X

More information

CSC 8301 Design and Analysis of Algorithms: Exhaustive Search

CSC 8301 Design and Analysis of Algorithms: Exhaustive Search CSC 8301 Design and Analysis of Algorithms: Exhaustive Search Professor Henry Carter Fall 2016 Recap Brute force is the use of iterative checking or solving a problem by its definition The straightforward

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

CSC384 Test 1 Sample Questions

CSC384 Test 1 Sample Questions CSC384 Test 1 Sample Questions October 27, 2015 1 Short Answer 1. Is A s search behavior necessarily exponentially explosive?. That is, does its search time always grow at least exponentially with the

More information

Class2: Constraint Networks Rina Dechter

Class2: Constraint Networks Rina Dechter Algorithms for Reasoning with graphical models Class2: Constraint Networks Rina Dechter Dbook: chapter 2-3, Constraint book: chapters 2 and 4 Text Books Road Map Graphical models Constraint networks Model

More information

Algorithm Design Techniques. Hwansoo Han

Algorithm Design Techniques. Hwansoo Han Algorithm Design Techniques Hwansoo Han Algorithm Design General techniques to yield effective algorithms Divide-and-Conquer Dynamic programming Greedy techniques Backtracking Local search 2 Divide-and-Conquer

More information

In this chapter we will very briefly review the most common algorithmic techniques which are used in bioinformatics.

In this chapter we will very briefly review the most common algorithmic techniques which are used in bioinformatics. Algorithm Techniques In this chapter we will very briefly review the most common algorithmic techniques which are used in bioinformatics. Bioinfo I (Institut Pasteur de Montevideo) Algorithm Techniques

More information

Graphs. Directed graphs. Readings: Section 28

Graphs. Directed graphs. Readings: Section 28 Graphs Readings: Section 28 CS 135 Winter 2018 12: Graphs 1 Directed graphs A directed graph consists of a collection of vertices (also called nodes) together with a collection of edges. An edge is an

More information

UNIT 5 BACKTRACKING. BACKTRACKING (General Method)

UNIT 5 BACKTRACKING. BACKTRACKING (General Method) UNIT 5 BACKTRACKING BACKTRACKING (General Method) Definition Depth First node generation with bounding function is called backtracking. Suppose mi is the size of set S i. Then there are m=m1,m2..m n n-tuples

More information

Lecture 6: Recursion RECURSION

Lecture 6: Recursion RECURSION Lecture 6: Recursion RECURSION You are now Java experts! 2 This was almost all the Java that we will teach you in this course Will see a few last things in the remainder of class Now will begin focusing

More information

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Question Bank Subject Name: CS6402- Design & Analysis of Algorithm Year/Sem : II/IV UNIT-I INTRODUCTION

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Question Bank Subject Name: CS6402- Design & Analysis of Algorithm Year/Sem : II/IV UNIT-I INTRODUCTION Chendu College of Engineering & Technology (Approved by AICTE, New Delhi and Affiliated to Anna University) Zamin Endathur, Madurantakam, Kancheepuram District 603311 +91-44-27540091/92 www.ccet.org.in

More information

Introduction to Computer Science II CS S-16 Recursion III

Introduction to Computer Science II CS S-16 Recursion III Introduction to Computer Science II CS112-2012S-16 Recursion III David Galles Department of Computer Science University of San Francisco 16-0: Recursion Review Steps to solving a problem recusively What

More information

Data Structures, Algorithms & Data Science Platforms

Data Structures, Algorithms & Data Science Platforms Indian Institute of Science Bangalore, India भ रत य व ज ञ न स स थ न ब गल र, भ रत Department of Computational and Data Sciences DS221 19 Sep 19 Oct, 2017 Data Structures, Algorithms & Data Science Platforms

More information

CS 161 Fall 2015 Final Exam

CS 161 Fall 2015 Final Exam CS 161 Fall 2015 Final Exam Name: Student ID: 1: 2: 3: 4: 5: 6: 7: 8: Total: 1. (15 points) Let H = [24, 21, 18, 15, 12, 9, 6, 3] be an array of eight numbers, interpreted as a binary heap with the maximum

More information

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1 Graphs Readings: Section 28 CS 135 Fall 2018 12: Graphs 1 Directed graphs A directed graph consists of a collection of vertices (also called nodes) together with a collection of edges. An edge is an ordered

More information

Midterm Examination CS540-2: Introduction to Artificial Intelligence

Midterm Examination CS540-2: Introduction to Artificial Intelligence Midterm Examination CS540-2: Introduction to Artificial Intelligence March 15, 2018 LAST NAME: FIRST NAME: Problem Score Max Score 1 12 2 13 3 9 4 11 5 8 6 13 7 9 8 16 9 9 Total 100 Question 1. [12] Search

More information

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages Recursion Solution Counting Things Searching an Array Organizing Data Backtracking Defining Languages 1 Recursion Solution 3 RECURSION SOLUTION Recursion An extremely powerful problem-solving technique

More information

Search means finding a path or traversal between a start node and one of a set of goal nodes. Search is a study of states and their transitions.

Search means finding a path or traversal between a start node and one of a set of goal nodes. Search is a study of states and their transitions. UNIT 3 BASIC TRAVERSAL AND SEARCH TECHNIQUES Search means finding a path or traversal between a start node and one of a set of goal nodes. Search is a study of states and their transitions. Search involves

More information

Lecture 1. Introduction

Lecture 1. Introduction Lecture 1 Introduction 1 Lecture Contents 1. What is an algorithm? 2. Fundamentals of Algorithmic Problem Solving 3. Important Problem Types 4. Fundamental Data Structures 2 1. What is an Algorithm? Algorithm

More information

Constraint Satisfaction Problems. Chapter 6

Constraint Satisfaction Problems. Chapter 6 Constraint Satisfaction Problems Chapter 6 Constraint Satisfaction Problems A constraint satisfaction problem consists of three components, X, D, and C: X is a set of variables, {X 1,..., X n }. D is a

More information

Dynamic Programming. Outline and Reading. Computing Fibonacci

Dynamic Programming. Outline and Reading. Computing Fibonacci Dynamic Programming Dynamic Programming version 1.2 1 Outline and Reading Matrix Chain-Product ( 5.3.1) The General Technique ( 5.3.2) -1 Knapsac Problem ( 5.3.3) Dynamic Programming version 1.2 2 Computing

More information

Trees, Trees and More Trees

Trees, Trees and More Trees Trees, Trees and More Trees August 9, 01 Andrew B. Kahng abk@cs.ucsd.edu http://vlsicad.ucsd.edu/~abk/ How You ll See Trees in CS Trees as mathematical objects Trees as data structures Trees as tools for

More information

N N Sudoku Solver. Sequential and Parallel Computing

N N Sudoku Solver. Sequential and Parallel Computing N N Sudoku Solver Sequential and Parallel Computing Abdulaziz Aljohani Computer Science. Rochester Institute of Technology, RIT Rochester, United States aaa4020@rit.edu Abstract 'Sudoku' is a logic-based

More information

Functional Programming

Functional Programming 14 Functional Programming Exercises 14.1 a. 5 5 = 25 b. ((λy.3 + y + z)2) = 3 + 2 + z = 5 + z c. (λv.(λw.w)(y(λz.z))) 14.2 The results are the same. In part b, where there are two beta reductions, lazy

More information

Lecture 24: More Reductions (1997) Steven Skiena. skiena

Lecture 24: More Reductions (1997) Steven Skiena.   skiena Lecture 24: More Reductions (1997) Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794 4400 http://www.cs.sunysb.edu/ skiena Prove that subgraph isomorphism

More information

CS 106X, Lecture 10 Recursive Backtracking

CS 106X, Lecture 10 Recursive Backtracking CS 106X, Lecture 10 Recursive Backtracking reading: Programming Abstractions in C++, Chapter 9 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons

More information

Part I Basic Concepts 1

Part I Basic Concepts 1 Introduction xiii Part I Basic Concepts 1 Chapter 1 Integer Arithmetic 3 1.1 Example Program 3 1.2 Computer Program 4 1.3 Documentation 5 1.4 Input 6 1.5 Assignment Statement 7 1.5.1 Basics of assignment

More information

State Space Search. Many problems can be represented as a set of states and a set of rules of how one state is transformed to another.

State Space Search. Many problems can be represented as a set of states and a set of rules of how one state is transformed to another. State Space Search Many problems can be represented as a set of states and a set of rules of how one state is transformed to another. The problem is how to reach a particular goal state, starting from

More information

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1] CSCI1101 Final Exam December 18, 2018 Solutions 1. Determine the value and type of each of the expressions below. If the question has two lines, assume that the statement in the first line is executed,

More information

Picking up tennis balls

Picking up tennis balls Picking up tennis balls Called a traveling-salesman tour. Computing the best tour is an infamously difficult computational problem. Traveling-salesman problem http://xkcd.com/399/ (Randall Munro) What

More information

Branch and Bound. Live-node: A node that has not been expanded. It is similar to backtracking technique but uses BFS-like search.

Branch and Bound. Live-node: A node that has not been expanded. It is similar to backtracking technique but uses BFS-like search. Branch and Bound Definitions: Branch and Bound is a state space search method in which all the children of a node are generated before expanding any of its children. Live-node: A node that has not been

More information

Basic Search Algorithms

Basic Search Algorithms Basic Search Algorithms Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Abstract The complexities of various search algorithms are considered in terms of time, space, and cost

More information

Parallelizing SAT Solver With specific application on solving Sudoku Puzzles

Parallelizing SAT Solver With specific application on solving Sudoku Puzzles 6.338 Applied Parallel Computing Final Report Parallelizing SAT Solver With specific application on solving Sudoku Puzzles Hank Huang May 13, 2009 This project was focused on parallelizing a SAT solver

More information

Dynamic Programming Homework Problems

Dynamic Programming Homework Problems CS 1510 Dynamic Programming Homework Problems 1. Consider the recurrence relation T(0) = T(1) = 2 and for n > 1 n 1 T(n) = T(i)T(i 1) i=1 We consider the problem of computing T(n) from n. (a) Show that

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Introduction graph theory useful in practice represent many real-life problems can be if not careful with data structures Chapter 9 Graph s 2 Definitions Definitions an undirected graph is a finite set

More information

Index. optimal package assignments, 143 optimal package assignments, symmetrybreaking,

Index. optimal package assignments, 143 optimal package assignments, symmetrybreaking, A Abstract approach, 79 Amphibian coexistence aquarium, 7 executes, 16 model, 13 15 modeling languages, 11 12 MPSolver, 12 OR-Tools library, 12 preys, 7 run a model, 17 18 solution, 17 three-step approach,

More information

CMPSCI 250: Introduction to Computation. Lecture #24: General Search, DFS, and BFS David Mix Barrington 24 March 2014

CMPSCI 250: Introduction to Computation. Lecture #24: General Search, DFS, and BFS David Mix Barrington 24 March 2014 CMPSCI 250: Introduction to Computation Lecture #24: General Search, DFS, and BFS David Mix Barrington 24 March 2014 General Search, DFS, and BFS Four Examples of Search Problems State Spaces, Search,

More information

Theorem 2.9: nearest addition algorithm

Theorem 2.9: nearest addition algorithm There are severe limits on our ability to compute near-optimal tours It is NP-complete to decide whether a given undirected =(,)has a Hamiltonian cycle An approximation algorithm for the TSP can be used

More information

Recursion. Recursion is: Recursion splits a problem:

Recursion. Recursion is: Recursion splits a problem: Recursion Recursion Recursion is: A problem solving approach, that can... Generate simple solutions to... Certain kinds of problems that... Would be difficult to solve in other ways Recursion splits a

More information

CS 4100 // artificial intelligence

CS 4100 // artificial intelligence CS 4100 // artificial intelligence instructor: byron wallace Constraint Satisfaction Problems Attribution: many of these slides are modified versions of those distributed with the UC Berkeley CS188 materials

More information