CSC 427: Data Structures and Algorithm Analysis. Fall 2006

Similar documents
CSC 427: Data Structures and Algorithm Analysis. Fall Greedy algorithms. Greedy algorithms

Algorithm classification


CSC 421: Algorithm Design & Analysis. Spring 2015

Practice Problems for the Final

Lecture 6: Recursion RECURSION

Lecture 14: General Problem-Solving Methods

Efficiency and Recursion. We determine the efficiency of an algorithm by seeing by how much the algorithm s runtime varies with the problem size.

Recursion Revisited; Recursive Backtracking

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Constraint Satisfaction Problems. Chapter 6

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

Foundation Exam - Sample Problems for New Topics

Test 6. moodle.yorku.ca CSE 1020

CSE 143 Lecture 18. More Recursive Backtracking. slides created by Marty Stepp

Backtracking and Branch-and-Bound

4/16/2012. Data Compression. Exhaustive search, backtracking, object-oriented Queens. Check out from SVN: Queens Huffman-Bailey.

Search and Optimization

CS 4100/5100: Foundations of AI

Artificial Intelligence Constraint Satisfaction Problems

Constraint Satisfaction Problems

Constraint Satisfaction Problems (CSPs)

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

COMP Data Structures

Subset sum problem and dynamic programming

Constraint Satisfaction Problems

EXAM Computer Science 1 Part 1

Algorithms Interview Questions

Backtracking. See Section 7.7 p of Weiss

CSC 421: Algorithm Design & Analysis. Spring 2015

Design and Analysis of Algorithms

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Lecture 18. Questions? Monday, February 20 CS 430 Artificial Intelligence - Lecture 18 1

CS 302: Introduction to Programming in Java. Lecture 15

CSE 2123 Recursion. Jeremy Morris

About this exam review

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

Constraint Satisfaction Problems

COMP Homework #5. Due on April , 23:59. Web search-engine or Sudoku (100 points)

Data Structures and Algorithms Notes

CSC 222: Object-Oriented Programming. Fall 2015

Trees, Trees and More Trees

Branch & Bound (B&B) and Constraint Satisfaction Problems (CSPs)

CSCI2100B Data Structures Heaps

CS 206 Introduction to Computer Science II

Data Structures, Algorithms & Data Science Platforms

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

Unit-2 Divide and conquer 2016

TOTAL CREDIT UNITS L T P/ S SW/F W. Course Title: Analysis & Design of Algorithm. Course Level: UG Course Code: CSE303 Credit Units: 5

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

CSC 222: Object-Oriented Programming. Spring 2012

Recursion. Recursion is: Recursion splits a problem:

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

Lecture Chapter 6 Recursion as a Problem Solving Technique

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Algorithmic patterns

CSC 421: Algorithm Design and Analysis. Spring 2017

CSE 373 Final Exam 3/14/06 Sample Solution

Recursion. James Brucker

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

Homework 7: Sudoku. Preliminaries. Overview

6. Algorithm Design Techniques

PRACTICE MIDTERM EXAM #2

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

CS 314 Exam 2 Spring

Greedy Algorithms. Alexandra Stefan

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

CP222 Computer Science II. Searching and Sorting

Sankalchand Patel College of Engineering - Visnagar Department of Computer Engineering and Information Technology. Assignment

Chapter 16: Greedy Algorithm

Lecture Notes on Tries

Design and Analysis of Algorithms

Sorting. Task Description. Selection Sort. Should we worry about speed?

Problem solving paradigms

106B Final Review Session. Slides by Sierra Kaplan-Nelson and Kensen Shi Livestream managed by Jeffrey Barratt

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

CS 161 Fall 2015 Final Exam

CAD Algorithms. Categorizing Algorithms

Search,Sort,Recursion

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Searching and Sorting

2. (a) Explain when the Quick sort is preferred to merge sort and vice-versa.

DUKE UNIVERSITY Department of Computer Science. Test 2: CompSci 100e

Backtracking. Chapter 5

CSE332: Data Abstractions Lecture 4: Priority Queues; Heaps. James Fogarty Winter 2012

Module 4. Constraint satisfaction problems. Version 2 CSE IIT, Kharagpur

Union Find and Greedy Algorithms. CSE 101: Design and Analysis of Algorithms Lecture 8

CSC 222: Object-Oriented Programming Spring 2012

Recursion. Chapter 11. Chapter 11 1

CSC 421: Algorithm Design Analysis. Spring 2017

CS 206 Introduction to Computer Science II

Scan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

CS 320: Concepts of Programming Languages

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

CSE Theory of Computing Fall 2017 Project 1-SAT Solving

11. Recursion. n (n 1)!, otherwise. Mathematical Recursion. Recursion in Java: Infinite Recursion. 1, if n 1. n! =

DS ata Structures Aptitude

Towards a Memory-Efficient Knapsack DP Algorithm

Transcription:

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: the divide & conquer approach tackles a complex problem by breaking it into smaller pieces, solving each piece, and combining them into an overall solution e.g., merge sort divided the list into halves, conquered (sorted) each half, then merged the results e.g., to count number of nodes in a binary tree, break into counting the nodes in each subtree (which are smaller), then adding the results + 1 divide & conquer is applicable when a problem can naturally be divided into independent pieces sometimes, the pieces to be conquered can be handled in sequence i.e., arrive at a solution by making a sequence of choices/actions in these situations, we can consider specialized classes of algorithms greedy algorithms backtracking algorithms 2 1

Greedy algorithms the greedy approach to problem solving involves making a sequence of choices/actions, each of which simply looks best at the moment local view: choose the locally optimal option hopefully, a sequence of locally optimal solutions leads to a globally optimal solution example: optimal change given a monetary amount, make change using the fewest coins possible amount = 16 amount = 96 coins? coins? 3 Example: greedy change while the amount remaining is not 0: select the largest coin that is the amount remaining add a coin of that type to the change subtract the value of that coin from the amount remaining e.g., 96 = 50 + 25 + 10 + 10 + 1 will this greedy algorithm always yield the optimal solution? for U.S. currency, the answer is YES for arbitrary coin sets, the answer is NO suppose the U.S. Treasury added a 12 coin GREEDY: 16 = 12 + 1 + 1 + 1 + 1 OPTIMAL: 16 = 10 + 5 + 1 (5 coins) (3 coins) 4 2

Greed is good? IMPORTANT: the greedy approach is not applicable to all problems but when applicable, it is very effective (no planning or coordination necessary) example: job scheduling suppose you have a collection of jobs to execute and know their lengths want to schedule the jobs so as to minimize waiting time Job 1: 5 minutes Schedule 1-2-3: 0 + 5 + 15 = 20 minutes waiting Job 2: 10 minutes Schedule 3-2-1: 0 + 4 + 14 = 18 minutes waiting Job 3: 4 minutes Schedule 3-1-2: 0 + 4 + 9 = 13 minutes waiting GREEDY ALGORITHM: do the shortest job first i.e., while there are still jobs to execute, schedule the shortest remaining job does the greedy algorithm guarantee the optimal schedule? efficiency? 5 Example: N-queens problem given an NxN chess board, place a queen on each row so that no queen is in jeopardy GREEDY algorithm: start with first row, find a valid position in current row, place a queen in that position then move on to the next row since queen placements are not independent, local choices do not necessarily lead to a global solution GREEDY does not work need a more wholistic approach 6 3

Generate & test we could take an extreme approach to the N-queens problem systematically generate every possible arrangement test each one to see if it is a valid solution this will work (in theory), but the size of the search space may be prohibitive 4x4 board 16 4 = 1,820 arrangements 8x8 board 64 8 = 131,198,072 arrangements 7 Backtracking if we were smart, we could greatly reduce the search space e.g., any board arrangement with a queen at (1,1) and (2,1) is invalid no point in looking at the other queens, so can eliminate 12 boards from consideration backtracking is a smart way of doing generate & test view a solution as a sequence of choices/actions when presented with a choice, pick one (similar to GREEDY) however, reserve the right to change your mind and backtrack to a previous choice (unlike GREEDY) you must remember alternatives: if a choice does not lead to a solution, back up and try an alternative eventually, backtracking will find a solution or exhaust all alternatives 8 4

Chessboard class we could define a class hierarchy for chess pieces ChessPiece is an abstract class that specifies the common behaviors of pieces Queen, Knight, Pawn, are derived from ChessPiece and implement specific behaviors ChessPiece King Queen Bishop Knight Rook Pawn public class ChessBoard { private ChessPiece[][] board; private int piececount; public ChessBoard(int size) { public ChessPiece get(int row, int col) { public void remove(int row, int col) { public void add(int row, int col, ChessPiece p) { public boolean injeopardy(int row, int col) {.. public int numpieces() { public int size() { public String tostring() { // 2-D array of chess pieces // number of pieces on the board // constructs size-by-size board // returns piece at (row,col) // removes piece at (row,col) // places a piece, e.g., a queen, // at (row,col) // returns true if (row,col) is // under attack by any piece // returns number of pieces on board // returns the board size // converts board to String 9 Backtracking N-queens /** * Fills the board with queens where none are jeopardy * @return true if able to successfully fill all rows */ public boolean placequeens() { return this.placequeens(0); /** * Fills the board with queens starting at specified row * (Queens have already been placed in rows 0 to row-1) */ private boolean placequeens(int row) { if (row >= this.size()) { return true; else { for (int col = 0; col < this.size(); col++) { if (!this.injeopardy(row, col)) { this.add(row, col, new Queen()); if (this.placequeens(row+1)) { return true; else { this.remove(row, col); return false; could add a method for placing queens, which calls a private (recursive backtracking) helper method BASE CASE: if all queens have been placed, then done. OTHERWISE: try placing queen in the row and recurse to place the rest note: if recursion fails, must remove the queen in order to backtrack 10 5

Why does backtracking work? backtracking burns no bridges all choices are reversible think of the search space as a tree root is the initial state of the problem (e.g., empty board) at each step, multiple choices lead to a branching of the tree solution is a sequence of choices (path) that leads from start state to a goal state 11 backtracking vs. generate & test backtracking provides a systematic way of trying all paths (sequences of choices) until a solution is found worst case: exhaustively tries all paths, traversing the entire search space backtracking is different from generate & test in that choices are made sequentially earlier choices constrain later ones can avoid searching entire branches 12 6

Boggle backtracking in the boggle code, backtracking was used to search the entire board for all words findallwords() : starts a fresh search for each position on the board findallwords(sofar, row, col) : checks to see if (row,col) is valid, then adds the char at (row,col) to the string sofar checks to see if that is a word & adds to set if it is checks to see if that is a prefix of a word & continues the recursive search if it is (note: replaces char with '*' to avoid reuse) private void findallwords() { for (int row = 0; row < this.board.length; row++) { for (int col = 0; col < this.board.length; col++) { this.findallwords("", row, col); private void findallwords(string sofar, int row, int col) { if (row >= 0 && row < this.board.length && col >= 0 && col < this.board.length && this.board[row][col]!= '*') { sofar += this.board[row][col]; if (this.dictionary.contains(sofar)) { this.words.add(sofar); if (this.dictionary.containsprefix(sofar)) { char saved = this.board[row][col]; this.board[row][col] = '*'; this.findallwords(sofar, row-1, col-1); this.findallwords(sofar, row-1, col); this.findallwords(sofar, row-1, col+1); this.findallwords(sofar, row, col-1); this.findallwords(sofar, row, col+1); this.findallwords(sofar, row+1, col-1); this.findallwords(sofar, row+1, col); this.findallwords(sofar, row+1, col+1); this.board[row][col] = saved; 13 Boggle (v. 2) note: the recursive search could have been structured differently instead of searching the board for sequences & checking to see if in dictionary, could have traversed the dictionary & checked to see if each word was in board tradeoffs? private void findallwords() { for (String word : this.dictionary) { if (this.findword(word)) { this.words.add(word); private boolean findword(string word) { for (int row = 0; row < this.board.length; row++) { for (int col = 0; col < this.board.length; col++) { if (this.findword(word, row, col)) { return true; return false; private boolean findword(string word, int row, int col) { if (word.equals("")) { return true; else if (row < 0 row >= this.board.length col < 0 col >= this.board.length this.board[row][col]!= word.charat(0)) { return false; else { char safe = this.board[r][c]; this.board[r][c] = '*'; String rest = word.substring(1); boolean result = (this.findword(rest, r-1, c-1) this.findword(rest, r-1, c) this.findword(rest, r-1, c+1) this.findword(rest, r, c-1) this.findword(rest, r, c+1) this.findword(rest, r+1, c-1) this.findword(rest, r+1, c) this.findword(rest, r+1, c+1)); this.board[r][c] = safe; return result; 14 7

Another example: blob count application: 2-D gel electrophoresis biologists use electrophoresis to produce a gel image of cellular material each "blob" (contiguous collection of dark pixels) represents a protein identify proteins by matching the blobs up with another known gel image we would like to identify each blob, its location and size location is highest & leftmost pixel in the blob size is the number of contiguous pixels in the blob in this small image: Blob at [0][1]: size 5 Blob at [2][7]: size 1 Blob at [6][0]: size 4 Blob at [6][6]: size 4 can use backtracking to locate & measure blobs 15 Finding blobs public void findblobs() { for (int row = 0; row < this.grid.length; row++) { for (int col = 0; col < this.grid.length; col++) { if (this.grid[row][col] == '*') { System.out.println("Blob at [" + row + "][" + findblobs traverses the image, checks each grid pixel for a blob blobsize uses backtracking to expand in all directions once a blob is found note: each pixel is "erased" after it is processed to avoid double-counting (& infinite recursion) the image is restored at the end of findblobs col + "] : size " + this.blobsize(row, col)); for (int row = 0; row < this.grid.length; row++) { for (int col = 0; col < this.grid.length; col++) { if (this.grid[row][col] == 'O') { this.grid[row][col] = '*'; private int blobsize(int row, int col) { if (row < 0 row >= this.grid.length col < 0 col >= this.grid.length this.grid[row][col]!= '*') { return 0; else { this.grid[row][col] = 'O'; return 1 + this.blobsize(row-1, col-1) + this.blobsize(row-1, col) + this.blobsize(row-1, col+1) + this.blobsize( row, col-1) + this.blobsize( row, col+1) + this.blobsize(row+1, col-1) + this.blobsize(row+1, col) + this.blobsize(row+1, col+1); 16 8

HW6: Sudoku solver for HW6, you are to design and implement a program for solving Sudoku puzzles you will need to create a class for representing the board, including a method for solving the board via recursive backtracking while there are any empty spots pick an empty spot & place a number in it if a conflict occurs, backtrack you will also need to create a GUI for entering the initial board & displaying the solution surprisingly: simple, blind backtracking is sufficient for solving even the hardest Sudoku puzzle almost instantaneously 17 9