07c backtracking

Upload: frankjamison

Post on 04-Jun-2018

243 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 07c BackTracking

    1/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 1

    More on

    Stacks and Queues

    and

    Backtracking

  • 8/13/2019 07c BackTracking

    2/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 2

    As we mentioned before, two common introductory

    Abstract Data Type (ADT) that worth studying are Stack

    and Queue

    Many problems (or parts of problems) can be thought of as

    stack problems, queue problems, or other problems that can

    be solved with the help of another (perhaps user-defined)ADT

    You need to decide what ADTs you need, build them, testthem, then tackle your larger problem

  • 8/13/2019 07c BackTracking

    3/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 3

    Stack ADT

    A stack is an ADT with specific properties and operations

    Stack properties are: Only one item can be accessed at a time

    Always the last item inserted is the first to come out (LIFO)

    New items must be inserted at the top

    The size of the stack is dynamic

    The stack must be able to grow and shrink

    Normally, items stored on the stack are homogeneous (i. e.they are all integers or all are string, etc

  • 8/13/2019 07c BackTracking

    4/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 4

    Stack Operations

    Stack operations are:

    Push:Puts a new item on the top of the stack. Cant pushinto a full stack

    Pop:Removes the top item from stack. Cant pop an

    empty stack

    Top:Examine top item without modifying stack. Cant topan empty stack

    Init:Set existing stack to empty

    Full:Returns true if the stack is full

    Empty:Returns true if the stack is empty

  • 8/13/2019 07c BackTracking

    5/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 5

    Problem Solving Using Stack:

    Bracket Checking

    Many problems can be solved using stacks

    Given a mathematical expression with 3 types of brackets ( ) [ ]

    { }, we want to determine if the brackets are properly matched

    For example, bracketing in the following expression is CORRECT

    { 5 * (8-2) } / { [4 * (3+2)] + [5 * 6] }

    However, the bracketing in the following two expressions areINCORRECT

    { (A+C) * D

    [A + {B+C} )

  • 8/13/2019 07c BackTracking

    6/28

    Dr. Ahmad R. Hadaegh

    A.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 6

    This problem is easily solved with a stack

    Algorithm:

    Scan expression from left to right

    Each time a left bracket is encountered, push it onto thestack

    When a right bracket is encountered, compare it to the topitem on the stack

    If its a match, pop the stack

    If not, report illegal bracketing

    If the stack is prematurely empty, report illegal bracketing

    If there are items left on the stack after the expression hasbeen scanned, report illegal bracketing

  • 8/13/2019 07c BackTracking

    7/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 7

    bool BracketMaching (string expression)

    {

    char curr, temp;

    Stack bracket_stack;

    for (int i=0; i< stg.size(); i++){

    curr = stg[i];

    if (curr == ( || curr == [ || curr == {)

    bracket_stack.push (curr);

    else if (curr == ) || curr == ] || curr == })if (bracket_stack.empty() ) then

    return false;

    else if (bracket_stack.pop() does not match with curr)

    return false;

    end if

    end if

    } // for loop

    return true;

    }

    This program assumes

    that we have the

    following routines

    available

    bool empty ();

    push (item);

    char top ();

  • 8/13/2019 07c BackTracking

    8/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 8

    Problem Solving Using Stack:

    Evaluation of An Expression

    Consider the problem of evaluating an arithmetic expression usinga stack

    Traditionally, when we write an arithmetic expression as follows:

    2 + 3 * (6 - 5)

    This is known as infix notation

    Operators are in-between the operands

    When computing arithmetic expressions, its sometimes useful to

    represent them using postfix (operator after) or prefix (operator

    before) notation

  • 8/13/2019 07c BackTracking

    9/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 9

    Prefix Infix Postfix

    - 6 1

    * + 4 3 2

    / + 2 3 - 9 4

    6 - 1

    (4 + 3) * 2

    (2 + 3) / (9 - 4)

    6 1 -

    4 3 + 2 *

    2 3 + 9 4 - /

    Its easy to evaluate postfix and prefix expressions using astack in part because no brackets are necessary

  • 8/13/2019 07c BackTracking

    10/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 10

    prefix postfix

    * + 4 3 2

    4

    3

    2

    4 3 + 2 *

    3

    4

    evaluate

    147

    2+

    *+

    2

    714*

    Push 2

    Push 3Push 4Pop 4Pop 3Apply + and get 7Push 7Pop 7Pop 2Apply * and get 14

    Push 14

    push 4

    push 3

    Pop 3

    Pop 4

    Apply addition and get 7

    Push 7

    Push 2Pop 2

    Pop 7

    Apply * and get 14

    Push 14

  • 8/13/2019 07c BackTracking

    11/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 11

    Algorithm for evaluating postfix:

    Parse expression from left to right

    When an operand is encountered, push it onto the stack

    When an operator is encountered, pop the top twooperands, apply the operator, and push the result onto thestack

    When the expression is completely scanned, the finalresult will be on the stack

    What if we want to convert an expression from infix to

    postfix?

    For example:2 + 3 * [(5 - 6) / 2] becomes

    2 3 5 6 - 2 / * +

  • 8/13/2019 07c BackTracking

    12/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 12

    Use the following algorithm to change infix to postfix:

    Scan infix string from left to right

    Each time an operand is encountered, copy it to the output

    When a bracket is encountered, check its orientation. Push left brackets onto the stack If its a right bracket, pop all operators out of the stack and

    copy them to output until a matching left bracket isencountered. Discard the left bracket.

    When an operator is encountered, check the top item of thestack.

    If the priority is >= the current operator, pop the topoperator and copy it to output

    Continue until an operator of lesser priority is encountered

    or until stack is empty Assume left brackets have lowest priority Finally, push current operator onto the stack

    When the end of the expression is reached, copy the remainingstack contents to output in the order popped

  • 8/13/2019 07c BackTracking

    13/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 13

    Consider the following example that is scanned from left to right

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    2 is placed on the output

    line because it is an

    operand

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    + is an operator and it is placedin the stack. Note there is no

    operator on the top of the stack

    with priority >= the + operator+

    2

    2

  • 8/13/2019 07c BackTracking

    14/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 14

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    3 is placed on the output

    line because it is an

    operand+

    2 3

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    * is an operator and it is placedin the stack without taking

    anything out of the stack. Note

    that * has higher priority than +

    *

    2 3

    +

  • 8/13/2019 07c BackTracking

    15/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 15

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    Left brackets, no matter whattype of bracket it is, it is placed

    in the stack*

    2 3

    +

    [

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    Again another left encountered

    and it is placed in the stack*

    2 3

    +

    [

    (

  • 8/13/2019 07c BackTracking

    16/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 16

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    5 is placed on the output line

    because it is an operand*

    2 3 5

    +

    [(

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    Minus sign (-) is placed in the

    stack. Note that the top of the

    stack is not an operator to

    compare minus sign with it

    *

    2 3 5

    +

    [

    (

    -

  • 8/13/2019 07c BackTracking

    17/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 17

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    6 is placed on the output line

    because it is an operand*

    2 3 5 6

    +

    [

    (

    -

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    ( is a closing roundbracket. Keep onpopping from the stack till we you find

    the matching opening roundbracket.

    DO NOT COPY THE OPEN ROUND

    BRACKET TO THE OUTPUT

    *

    2 3 5 6 -

    +

    [

  • 8/13/2019 07c BackTracking

    18/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 18

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    Division (/) is placed in the stack.Note that the top of the stack is

    not an operator to compare

    division sign with it

    *

    2 3 5 6 -

    +

    [

    /

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    2 is placed on the output line

    because it is an operand*

    2 3 5 6 - 2

    +

    [

    /

  • 8/13/2019 07c BackTracking

    19/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 19

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    ] is a closingsquarebracket. Keep on

    popping from the stack till we you find

    the matching openingsquarebracket.

    DO NOT COPY THE OPEN SQUARE

    BRACKET TO THE OUTPUT

    *

    2 3 5 6 - 2 /

    +

    Expression:

    2 + 3 * [ ( 56 ) / 2 ]

    StackOutput:

    We are done. So keep popping

    from the stack and place thecharacters to the output line

    2 3 5 62 / * +

    What we have on the output line is the corresponding postfixexpression

  • 8/13/2019 07c BackTracking

    20/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 20

    Problem Solving Using Stack:

    Adding large numbers using stack

    Another example of stack application is adding two large numberstogether.

    Note that the largest magnitude of integers are limited so we are

    not able to normally add numbers like:

    243678489505654679857465758598595950949463535 +

    462668435748955758056548577946

    Since the integer variables cannot hold such a big numbers we can

    use other tools to add these numbers together

    The next slide shows the algorithm of adding two numbers

    together using stack

  • 8/13/2019 07c BackTracking

    21/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 21

    Algorithm for adding two numbers

    Read the numerals of the first number and store the numbers

    corresponding to them on the stack;

    Read the numerals of the second number and store them in anotherstack;

    Let R = 0;

    While at least one stack is not empty Pop a number from each stack and add them to R; Push the unitpart of R on the result stack;

    Store carrypart of R in R overwriting the old value;

    Push R on the result stack if it is not zero

    Pop numbers from the result stack and display them

    2 1

  • 8/13/2019 07c BackTracking

    22/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 22

    592

    + 3784

    4376

    29

    5

    4

    8

    7

    3

    2

    + 4

    6

    9

    + 8

    17

    15

    + 713

    9

    5

    8

    7

    3

    6

    5

    7

    3

    7

    6

    3

    3

    7

    6

    Stack 1

    Stack 2

    Result

    Stack

    4

    3

    7

    6

    + =6 + =17 + =13 + =4

    1

    + 3

    4

  • 8/13/2019 07c BackTracking

    23/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 23

    Problem Solving Using Stack:Exiting A Maze Consider the problem of a trapped mouse that tries to find its way

    to an exit in a maze

    The mouse systematically moves and if it hits a wall, it backtracksand tries another path.

    The maze is implemented as a two dimensional character array inwhich passages are marked with oand walls are marked with

    1. When a cell is visited, it is marked with .so that the mouse does

    not try that again.

    In general, the mouse always takes right cell first, if it cannot

    succeed, it takes left and if it still fails, it takes down and finally ittries the upper cell to reach its destination.

    As long as it finds a space it moves in that path and tries its best tofind the exit door.

    We represent the mouse with Mand exit door with E

  • 8/13/2019 07c BackTracking

    24/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 24

    In order to ensure that the mouse does not fall off the maze, wecreate a wall around the maze.

    Thus the mouse will be trapped in the maze until it finds the door.

    If the mouse tries all the possible solutions and still cannot find theexit door, we report a failure; otherwise, we report a success.

    The algorithm is:

    Initialize stack, exitCell, entryCell, currentCell = entryCell;Create a wall of 1s around the mazeWhile currentCell is not exitCell

    Mark currentCell as visited;Push onto the stack the unvisited neighbors of current Cell in theorder of up, down left and rightIf stack is empty

    Report failureElse

    Pop off a cell from the stack and make it currentCellsuccess

  • 8/13/2019 07c BackTracking

    25/28Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 25

    1 1 1 1 1 1

    1 1 1 o o 1

    1 o o o E 1

    1 o o M 1 1

    1 1 1 1 1 1

    0

    1

    2

    3

    4

    0 1 2 3 4 5

    (3, 2)

    (2, 3)

    Push the Up and

    Left cell into stack

    Start with the following maze

    where the mouse is at position

    (3, 3) and the exit door is at(2, 4)

    1 1 1 1 1 1

    1 1 1 o o 1

    1 o o o E 1

    1 o o M 1 1

    1 1 1 1 1 1

    0

    1

    2

    34

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first element

    of the stack

    Move the mouse to

    that position

    0 1 2 3 4 5

  • 8/13/2019 07c BackTracking

    26/28

    Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 26

    Push the Up cell

    into stack1 1 1 1 1 1

    1 1 1 o o 1

    1 o o o E 1

    1 M . . 1 1

    1 1 1 1 1 1

    0

    12

    3

    4

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first element

    of the stack

    Move the mouse to

    that position

    (3, 1)(2, 2)

    (2, 3)

    Push the Up and

    Left cells into stack1 1 1 1 1 1

    1 1 1 o o 1

    1 o o o E 1

    1 o M . 1 1

    1 1 1 1 1 1

    0

    1

    2

    3

    4

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first elementof the stack

    Move the mouse to

    that position

    (2, 1)

    (2, 2)

    (2, 3)

    0 1 2 3 4 5

  • 8/13/2019 07c BackTracking

    27/28

    Dr. Ahmad R. HadaeghA.R. Hadaegh Cali for nia State University San Marcos (CSUSM) Page 27

    Push the Right

    cell into stack1 1 1 1 1 1

    1 1 1 o o 1

    1 . M o E 1

    1 . . . 1 1

    1 1 1 1 1 1

    0

    12

    3

    4

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first element

    of the stack

    Move the mouse to

    that position

    (2, 2)(2, 2)

    (2, 3)

    Push the Right

    cell into stack1 1 1 1 1 1

    1 1 1 o o 1

    1 M o o E 1

    1 . . . 1 1

    1 1 1 1 1 1

    0

    1

    2

    3

    4

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first elementof the stack

    Move the mouse to

    that position

    (2, 3)

    (2, 2)

    (2, 3)

    0 1 2 3 4 5

  • 8/13/2019 07c BackTracking

    28/28

    28

    Push the UP

    cell into stack1 1 1 1 1 1

    1 1 1 o o 1

    1 . . . E/M 1

    1 . . . 1 1

    1 1 1 1 1 1

    0

    12

    3

    4

    0 1 2 3 4 5

    The exit door is found

    (2, 4)(1, 3)

    (2, 2)

    (2, 3)

    Push the UP and

    Right cell into

    stack

    1 1 1 1 1 1

    1 1 1 o o 1

    1 . . M E 1

    1 . . . 1 1

    1 1 1 1 1 1

    0

    1

    2

    3

    4

    0 1 2 3 4 5Make the current

    position visited (.)

    Pop the first elementof the stack

    Move the mouse to

    that position

    (1, 3)

    (2, 2)

    (2, 3)