Chapter Five Recursion and Trees Recursion Divide and conquer Dynamic programming Trees and tree traversals Graphs and graph traversals Please read chapter.

Slides:



Advertisements
Similar presentations
Aside on AI Will computers ever be intelligent? Really intelligent?
Advertisements

S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Chapter 5 Decrease and Conquer. Homework 7 hw7 (due 3/17) hw7 (due 3/17) –page 127 question 5 –page 132 questions 5 and 6 –page 137 questions 5 and 6.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
CS 171: Introduction to Computer Science II
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Course Review COMP171 Spring Hashing / Slide 2 Elementary Data Structures * Linked lists n Types: singular, doubly, circular n Operations: insert,
Thoughts on AI Will computers ever be intelligent? Really intelligent? Tasks that previously were thought to require intelligence: adding and subtracting.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
Transforming Infix to Postfix
Module #1 - Logic 1 Based on Rosen, Discrete Mathematics & Its Applications. Prepared by (c) , Michael P. Frank and Modified By Mingwu Chen Trees.
Data Structures & Algorithms Recursion and Trees.
2/10/03Tucker, Sec Tucker, Applied Combinatorics, Sec. 3.2, Important Definitions Enumeration: Finding all of the possible paths in a rooted tree.
Backtracking.
Data Structures Using C++1 Chapter 11 Binary Trees.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
BCT 2083 DISCRETE STRUCTURE AND APPLICATIONS
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Introduction to search Chapter 3. Why study search? §Search is a basis for all AI l search proposed as the basis of intelligence l inference l all learning.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Aside on AI Will computers ever be intelligent? Really intelligent? Tasks that previously were thought to require intelligence: adding and subtracting.
1 Introduction to trees Instructor: Dimitrios Kosmopoulos.
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.
Trees Dr. B. Prabhakaran Application Examples Useful for locating items in a list Used in Huffman coding algorithm Study games like.
Starting at Binary Trees
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
IS 2610: Data Structures Recursion, Divide and conquer Dynamic programming, Feb 2, 2004.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
1 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Chapter 10: Trees A tree is a connected simple undirected graph with no simple circuits. Properties: There is a unique simple path between any 2 of its.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Symbol tables.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Graphs and Trees Mathematical Structures for Computer Science Chapter 5 Copyright © 2006 W.H. Freeman & Co.MSCS SlidesGraphs and Trees.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Now, Chapter 5: Decrease and Conquer Reduce problem instance to smaller instance of the same problem and extend solution Solve smaller instance Extend.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Chapter 11. Chapter Summary Introduction to Trees Applications of Trees (not currently included in overheads) Tree Traversal Spanning Trees Minimum Spanning.
Brute Force and Exhaustive Search Brute Force and Exhaustive Search Traveling Salesman Problem Knapsack Problem Assignment Problem Selection Sort and Bubble.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
CSE 373 Data Structures Lecture 7
Non Linear Data Structure
Trees Chapter 15.
Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos
DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
Week 6 - Wednesday CS221.
Data Structures Review Session 2
Data Structures & Algorithms
CMSC 202 Trees.
Design and Analysis of Algorithms
CSC 143 Java Trees.
Presentation transcript:

Chapter Five Recursion and Trees Recursion Divide and conquer Dynamic programming Trees and tree traversals Graphs and graph traversals Please read chapter 5.

Recursive algorithms What’s the runtime of this algorithm? int puzzle(int N) { if (N == 1) return 1; if (N % 2 == 0) return puzzle(N/2); else return puzzle(3 * n + 1); } Why is it hard to determine the runtime? Recursive algorithms need base case and recursive call(s) (preferably smaller!)

Euclid’s algorithm Suppose you write a first-class Fraction class Need to reduce fractions, such as 546/3185 Note that gcd(m,n) = gcd(n,m%n) gcd(3185,546) gcd(546,455) gcd(455,91) gcd(91,0)  return 91  return 91 code? int gcd(int m, int n) { if (n == 0) return m; return gcd(n, m%n); }

Fractals What is a fractal? self-similarity at a different level Koch SnowflakeKoch Snowflake: how to draw? 2D Fractal Star2D Fractal Star… Fractal flowers… /kochR { 2 copy ge {dup 0 rlineto } { 3 dif 2 copy kockR 60 rotate 2 copy kochR -120 rotate 2 copy kochR 60 rotate 2 copy kochR } ifelse pop pop } def 0 0 moveto kochR 0 27 moveto 9 81 kochR 0 54 moveto 3 81 kochR 0 81 moveto 1 81 kochR stroke

Divide and Conquer Split a problem into smaller subproblems Solve the subproblems recursively Merge the subproblem solutions into a solution to the whole problem The great point is to learn to solve a problem in terms of subproblem solutions.

Divide and Conquer Examples Merge sort Binary Search Towers of Hanoi Parsing HTML, XML pow(x,n) log(n,base) log*(n) Point-in-convex-polygon

Min & Max Given a set of n items, find the min and max. How many comparisons needed? Simple alg: n-1 comparisons to find min, n-1 for max Recursive algorithm: void minmax(int i, int j, int& min0, int& max0) if (j<=i+1) [handle base case; return] m=(i+j+1)/2; minmax(i,m-1,min1,max1); minmax(m,j,min2,max2); min0 = min(min1,min2); max0 = max(max1,max2); Recurrence:T(n)=2T(n/2) + 2; T(2)=1 Solution?1.5 n - 2

Multiplying How long does it take to multiply two n-bit numbers? Grade school algorithm: (a 2 n/2 + b)(c 2 n/2 + d) ac 2 n + (ad + bc)2 n/2 + bd T(n) = 4T(n/2) + c nO(n 2 ) Improvement: (a+b)(c+d) = ac + ad + bc + bd T(n)=3T(n/2) + c n O(n lg 3 ) Runtime?O(n 2 ) Recursive algorithm: How to solve in terms of subproblem solutions? Recurrence?

Fibonacci Numbers What is the Golden ratio? Can approximate with Fibonacci numbers. Mi to km conversion Pineapple raster, pine cone pattern… Recursive Fibonacci algorithm? Runtime Recurrence? T(1)=1; T(2)=1; T(n) = T(n-1) + T(n-2) + 1 Runtime? not sure…but at least  (2 n/2 ) How to improve runtime? compute bottom-up or just remember values you’ve already computed

Dynamic Programming Solve by combining solutions to overlapping subproblems Runtime of recursive solution is typically exponential Make the algorithm efficient: built a table bottom-up or memoize

DP Example: Making Change Making change Available coin values: v 1, v 2, v 3, …, v k How to make change totalling C with fewest coins? Base cases: mincoins(0)=0; mincoins(v 1 )=1, etc. Recursive step: mincoins(n)=min[ 1+mincoins(n-v 1 ), 1+mincoins(n-v 2 ), …, 1+mincoins(n-v k ) ] Runtime recurrence? How to make this algorithm efficient? table-based approach memoization

Algorithm design by Dynamic Programming 1. Identify subproblem solutions of interest. Name them. 2. Express solution to whole problem recursively, in terms of subproblem solutions 3. Memoize (or compute bottom-up) coin values v 1, v 2, …, v n mincoins(k)=smallest number of coins to totaling k in value mincoins(k) = 1 if k = v i, infinity if k < 1 mincoins(k) = min[mincoins(k-v 1 ), …, mincoins(k-v n ) ] + 1 jot down subproblem solutions as you compute them

DP Example: Weird Dice Given several weird dice. Roll probabilities? Dice have s 1, s 2, s 3, …, s n sides Count the number of ways you can roll each roll; divide by  s k Base case: rolling die number 1. What about 2 dice, 3, …? Subproblem solutions of interest? Rolls(n,i) = number of ways of rolling n with first i dice =Rolls(n-1, i-1) + Rolls(n-2,i-1) + … + Rolls(n-s k,i-1) Rolls(i,1) = 1, i=1..s i Runtime? O(  s k ) = O(n) if s k <= const.

Knapsack You are robbing a bank vault. How to maximize take? Items 1, 2, …, n have values v 1, v 2, …, v n and integer weights w 1, w 2, …, w n How to maximize take, if you can only carry B lbs? Subproblems of interest: maxval(w,k) = best value with weight w, objects a subset of 1..k Recursive solution? maxval(w,k) = max[maxval(w-1,k),maxval(w,k-1), maxval(w-w k,k-1)+v k ] maxval(w,0) = 0 want maxval(B,n) memoize or compute bottom up

Other Dynamic Programming applications Not-one strategies Shortest path Paragraph wrapping Matrix chain multiplication Polygon triangulation lots of optimization problems…

Graphs and Trees Graph: a set V of vertices (or nodes) and a set E of edges, a subset of VxV Digraph: a graph with directed edges Tree: a connected, acyclic graph with one node designated as root Sibling, parent, ancestor, descendent External node: “dummy” node or null pointer Leaf: a node with only external nodes as children

Graphs

Binary Trees Path: a list of connected vertices Height of a rooted tree: the length of the longest path from the root to a leaf Binary tree: a tree where each node has up to 2 children, called “left” and “right” Complete binary tree: a tree where all the leaves are at the same level Binary search tree (BST): a binary tree where the key of any node is greater than the keys of the nodes in its left subtree and less than those of its right subtree.

Tree Properties and Traversals How many edges in a tree of n nodes? n-1 How many external nodes in a tree of n nodes? n+1 Height of a binary tree with n nodes? between lg n and n-1 How can I visit every node of a tree? Traversals: preorder inorder postorder

Parse Trees How would one parse an arithmetic expression? Parse tree: a node for each operator leaves for operands Parse tree traversals: What does inorder traversal give? infix expression: (3+4)*(5-6) Postorder? postfix expression: – * Preorder? prefix expression: * – 5 6

Non-recursive Traversals How to implement a traversal non-recursively? What kind of traversal is this: void traverse(link n, void visit(link)) { STACK s(max); s.push(n); while (!s.empty()) { visit(n = s.pop()); if (n->right != 0) s.push(n->right); if (n->left != 0) s.push(n->left); }

Graph Traversals How do you find your way out of a maze, given a large supply of pennies? Graph traversals Depth-first search Breadth-first search Other applications: Boggle™, tic-tac-toe, path finding, theorem proving, motion planning, AI, …

Representing a Graph Two different drawings of the same graph are shown. What data structure to represent this graph?

Adjacency Matrix A B C D E F G H I J K L M A B C D E F G H I J K 0 0 L 1 M Space required for a graph with v vertices, e edges?  (e 2 ) Time to tell if there is an edge from v 1 to v 2 ?  (1)

Adjacency List A: F -> B -> C -> G B: A C: A D: E -> F E: D -> F -> G F: D -> E G: A -> E H: I I: H J: K -> L -> M K: J L: M -> J M: J -> L Space required for a graph with v vertices, e edges?  (v+e) Time to tell if there is an edge from v 1 to v 2 ?  (v)

Depth-first Search Main idea: keep traveling to a new, unvisited node until you you get stuck. Then backtrack as far as necessary and try a new path.

DFS: Recursive How to implement recursively? void dfs(link n, void visit(link)) { visit(n); visited[n]=1; for (link t=adj[k]; t!=0; t = t->next) if (!visited[t->v]) dfs(t->v, visit); visited[n]=2; } Runtime?O(e+v) for e edges, v vertices Space? O(v) – a path may be really long

DFS: Non-recursive How can you implement DFS non-recursively? Use a stack void dfs(link h, void visit(link)) { STACK s(max); s.push(h); while (!stack.empty()) if (!visited[n = s.pop()]) { visit(n); visited[n]=1; for (link t=adj[n]; t!=0; t=t->next) if (visited[t->v] == 0) s.push(t->v); visited[n]=2; }

Breadth-first Search Breadth-first search: Visit all neighbors of the start node (but don’t visit a node you’ve already seen). Then all neighbors of theirs, and of theirs, etc. Time? O(v+e) Space? O(v)

Breadth-first search How can you implement BFS? Use a queue with the DFS algorithm! void bfs(link h, void visit(link)) { QUEUE q(max); q.put(h); while (!q.empty()]) if (!visited[n = s.pop()]) { visit(n); visited[n]=1; for (link t=adj[n]; t!=0; t=t->next) if (visited[t->v] == 0) s.push(t->v); visited[n]=2; }

Aside on AI Will computers ever be intelligent? Really intelligent? Tasks that previously were thought to require intelligence: adding and subtracting playing chess driving a car recognizing speech or handwriting translating to a foreign language proving mathematical theorems What does it mean to say that a computer is intelligent? Is that the same as being a person? What is a person? Is a computer program a person? Is a person a computer program?

Achieving “Intelligence” How do AI program achieve “intelligent” behavior? Currently, three main paradigms: Symbolic knowledge representation and search Neural Nets Genetic Algorithms

Search in Artificial Intelligence Represent your problem as a graph where nodes are states and edges are operators that go between states Define problem states (nodes) Identify start and goal states Define operators (edges) Use DFS or BFS to find goal Example: Missionaries and cannibals problem states: (3,3,1)  3 missionaries, 3 cannibals, and 1 boat on left side of river. Operators: one or two people cross the river in the boat, so that there isn’t a cannibal majority on either side. Goal: get to the other side? Moves? (331)–(220)–(321)–(210)–(221)–(020)–(031)–(010)–(021)–(000)

DFS/BFS Resource Requirements DFS: Runtime? O(n), n=number of nodes expanded Space required? O(d), d = depth of search Can I cut off a search after 5 seconds? BFS: Runtime?O(n) Space required? O(breadth of tree) = O(b d ), b=branching factor Can I cut off a search after 5 seconds? Staged DFS: do a DFS of depth 1, 2, 3, … until out of time Runtime? O(n) Space required? O(d)

Game Playing We could use DFS but…can’t search whole tree! limit depth of search and use an evaluation function We could use DFS but…how do we know which move the opponent will choose? minimax algorithm: assume the opponent does what looks best. i.e. at nodes where it is the human’s turn, pick the move that looks best for human. Where computer’s turn, pick the move that looks best for the computer

Mankalah An ancient gamed called Kalah or Mankalah uses stones and pits: 6 to a side and one on each end. 4 stones are initially placed in each side pit. None are in the end pits (called Kalahs – a player’s kalah is on her right). A move consists of picking up the stones in a pit and distributing them, one at a time, in successive pits. If the last stone is placed in your Kalah, you go again If the last stone is placed in an empty pit on your side, you capture the stones in that pit and the opposite one, on the opponent’s side of the board. These are put into your Kalah. The game ends when one player has no stones left; the other player puts all the remaining stones on her side into her Kalah. Whoever ends with more stones in her Kalah wins. See the demo program on holmes at /home/hplantin/kalah.c  Write a smart kalah playing program!

Mankalah minimax int kalahboard::minimax(depth d): //semi-pseudocode if [human won] return –infinity; if [machine won] return +infinity; if (d==0) return evaluate(); if (whosemove==HUMAN) best=+infinity; for (move=first; move<=last; move++) kalahboard b=*this;//duplicate board if (b.board[move]>0)//is move legal? b.makemove(move);//make the move v=b.minimax(d-1);//find its value if (v<best) best=v;//remember if best else // similarly for MACHINE’s move return best;