110
1 SNU IDB Lab. Ch9. Stacks © copyright 2006 SNU IDB Lab.

DS Ch 9 (1 unit) Stacks

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: DS Ch 9 (1 unit) Stacks

1SNU

IDB Lab.

Ch9. Stacks© copyright 2006 SNU IDB Lab.

Page 2: DS Ch 9 (1 unit) Stacks

Data Structures 2SNU

IDB Lab.

Bird’s-Eye View (1/2)

� Chapter 9: Stack

� A kind of Linear list & LIFO(last-in-first-out) structure

� Insertion and removal from one end

� Chapter 10: Queue

� A kind of Linear list & FIFO(first-in-first-out) structure

� Insertion and deletion occur at different ends of the linear list

� Chapter 11: Skip Lists & Hashing

� Chains augmented with additional forward pointers

Page 3: DS Ch 9 (1 unit) Stacks

Data Structures 3SNU

IDB Lab.

Bird’s-Eye View (2/2)

� Stack Representation

� Array-based class “ArrayStack”

� Linked class “LinkedStack”

� Application using stack� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Switch Box Routing

� Offline Equivalence Class Problem

� Rat in a Maze

Page 4: DS Ch 9 (1 unit) Stacks

Data Structures 4SNU

IDB Lab.

Table of Contents

� Definition

� Array Representation of Stack

� Linked Representation of Stack

� Stack Applications

Page 5: DS Ch 9 (1 unit) Stacks

Data Structures 5SNU

IDB Lab.

Definition

� A stack is

� A kind of Linear list

� One end is called “top”

� Other end is called “bottom”

� Insertions and removals take place at the top

� A stack is a LIFO list (Last In First Out)

Page 6: DS Ch 9 (1 unit) Stacks

Data Structures 6SNU

IDB Lab.

Stack Application

� Stack of Cups

bottom

top

C

A

B

D

E

bottom

top

C

A

B

D

E

F

Insertion “F”

Page 7: DS Ch 9 (1 unit) Stacks

Data Structures 7SNU

IDB Lab.

The ADT StackAbstactDataType Stack{

instantceslinear list of elements; bottom; top;

operationsempty() : Return true if the stack is empty,

Return false otherwise;peek() : Return the top element;

push(x) : Add element x at the top;pop() : Remove the top element and return it;

}

Q: Can we think of any other core operation of the Stack?

Page 8: DS Ch 9 (1 unit) Stacks

Data Structures 8SNU

IDB Lab.

The Interface Stack

public interface Stack

{

public boolean empty();

public Object peek();

public void push(Object theObject);

public Object pop();

}

Page 9: DS Ch 9 (1 unit) Stacks

Data Structures 9SNU

IDB Lab.

Table of Contents

� Definition

� Array Representation

� Linked Representation

� Stack Applications

Page 10: DS Ch 9 (1 unit) Stacks

Data Structures 10SNU

IDB Lab.

The Class DerivedArrayStack (1)

� Derived from ArrayLinearList class

� Implements Stack interface

� The top is right end of array linear list

� push(theObject) � add (size(), theObject)

� O(1) time

� pop() � remove ( size() - 1)

� O(1) time

Page 11: DS Ch 9 (1 unit) Stacks

Data Structures 11SNU

IDB Lab.

The Class DerivedArrayStack (2)packagedataStructures;import java.util.*; // has stack exceptionpublicclass DerivedArrayStackextends ArrayLinearList

implements Stack{

publicDerivedArrayStack(int initialCapacity){super(initialCapacity);} //ArrayLinearList’s constructor

publicDerivedArrayStack(){ this(10);}

/* Stack interface methods come here */}

Page 12: DS Ch 9 (1 unit) Stacks

Data Structures 12SNU

IDB Lab.

public boolean empty () { returnisEmpty();}

publicObject peek (){ if (empty()) throw newEmptyStackException();

returnget(size() - 1) }

public void push (Object theElement){ add(size(), theElement); }

publicObject pop (){ if (empty()) throw newEmptyStackException();

returnremove(size() - 1); }

The Class DerivedArrayStack (3)

Page 13: DS Ch 9 (1 unit) Stacks

Data Structures 13SNU

IDB Lab.

The Class DerivedArrayStack (4)

� Stack as a subclass from ArrayLinearList class

� All public methods of ArrayLinearList may also be performed on a stack� For example, get(0)/remove(5)/add(3, x) are still alive� Thus, we do not have a true stack implementation

� So, need to override some undesired methods of ArrayLinearList� Public void add(int index, Object obj) {

throw new UNsupportedOperationException (“Not supported”)}

Page 14: DS Ch 9 (1 unit) Stacks

Data Structures 14SNU

IDB Lab.

The Class ArrayStack (1)

� A faster implementation of array-based stack

� Implement Only the methods of the Stack interface

� Uses an one-dimensional array

� push()/pop() : O(1) time

Page 15: DS Ch 9 (1 unit) Stacks

Data Structures 15SNU

IDB Lab.

The Class ArrayStack (2)packagedataStructures;import java.util.EmptyStackException;import utilities.*; // ChangeArrayLengthpublic class ArrayStackimplementsStack{ int top; // current top of stack

Object [] stack; // element array

publicArrayStack(int initialCapacity){if (initialCapacity < 1) throw newIllegalArgException ("initialCapacity must be >= 1");stack = newObject [initialCapacity]; // 1D array declarationtop = -1; }publicArrayStack() {this(10);}

/* Stack interface methods come here */}

Page 16: DS Ch 9 (1 unit) Stacks

Data Structures 16SNU

IDB Lab.

The Class ArrayStack (3)

public boleanempty () { returntop== -1; }

public Object peek () {if (empty()) throw newEmptyStackException();returnstack[top]; }

public voidpush (Object theElement){// increase(doubling) array size if necessaryif (top == stack.length - 1) stack = ChangeArrayLength.changeLength1D (stack, 2 * stack.length); stack[++top] = theElement; // put theElement at the top of the stack

}

publicObject pop () {if (empty()) throw newEmptyStackException();Object topElement = stack[top];stack[top--] = null; // enable garbage collectionreturntopElement;

}

Page 17: DS Ch 9 (1 unit) Stacks

Data Structures 17SNU

IDB Lab.

Performance Measurement� Time to perform a 500,000 sequence

� Stack took 2.6 times more of the time taken by ArrayStack

� The time spent resizing the array is approximately the same for all implementation(0.2 second)

0.22

0.38

0.33

1.04

-

0.44

0.60

0.55

1.27

1.15

ArrayStack

DerivedArrayStack

DerivedArrayStackWithCatch

DerivedVectorStack

Stack

500,00010Class

InitialCapacity

(Times are in seconds)

Page 18: DS Ch 9 (1 unit) Stacks

Data Structures 18SNU

IDB Lab.

Table of Contents

� Definition

� Array Representation

� Linked Representation

� Applications

Page 19: DS Ch 9 (1 unit) Stacks

Data Structures 19SNU

IDB Lab.

Multiple Stacks in an Array

� Two stacks in an array (space efficient)

� When more than two Stacks in an array� push() : the worst case can be O(length) � doubling the existing

array may involve a lot of complications

� pop() : O(1)

� If we have to save the space, why not pointers!

top1 top2

Stack1 Stack2

[0] [n]

n = element.length-1

Page 20: DS Ch 9 (1 unit) Stacks

Data Structures 20SNU

IDB Lab.

Chain for the Stack� Using a chain for each stack

� Operations of peek, push, pop method

� If top is the left-end of linear list

� get(0), add(0,x), remove(0) : O(1) time

� If top is the right-end of linear list

� get(size() –1), add(size(),x), remove(size() –1) : O(size()) time

� Use the left-end as stack top

a b c d enull

firstNode

Page 21: DS Ch 9 (1 unit) Stacks

Data Structures 21SNU

IDB Lab.

The Class DerivedLinkedStack� One possible implementation: derived from the class Chain

and implements the interface Stack

Public class DerivedLinkedStack extends Chain implements Stack

{// Replace the name DerivedArrayStack with the name DerivedLinkedStack// Change the parameter of the methods get(), remove(), add() to 0

}

� As we experienced in DerivedArrayStack, some operations in Chain are redundant and mismatch with the stack� So, we better use only the Stack interface

Page 22: DS Ch 9 (1 unit) Stacks

Data Structures 22SNU

IDB Lab.

The Class LinkedStack (1)

// want to implement only the stack interfacepackagedataStructures;import java.util.EmptyStackException;public class LinkedStackimplementsStack { // data members

protectedChainNode topNode;

/** create an empty stack */public LinkedStack (int initialCapacity)

{ // the default initial value of topNode is null}public LinkedStack ()

{ this(0);}

/* methods here */}

Page 23: DS Ch 9 (1 unit) Stacks

Data Structures 23SNU

IDB Lab.

The Class LinkedStack (2)public booleanempty() {

returntopNode == null;}

public Object peek() {if (empty()) throw newEmptyStackException();return topNode.element;

}

public voidpush(Object theElement) {topNode = newChainNode(theElement, topNode);

}

public Object pop() {if (empty()) throw newEmptyStackException();Object topElement = topNode.element;topNode = topNode.next;returntopElement;

}

Page 24: DS Ch 9 (1 unit) Stacks

Data Structures 24SNU

IDB Lab.

Performance Measurement

� LinkedStack is a little bit more efficient than DerivedLinkedStack because redundancies are removed

� To perform 500,000 sequence

� DerivedLinkedStack � 3.2 sec

� LinkedStack � 2.96 sec

� In general, LinkedStack requires more memory and time than ArrayStack

� So, the use of pointers (LinkedStack) provides no benefit when we deal with only a single stack

Page 25: DS Ch 9 (1 unit) Stacks

Data Structures 25SNU

IDB Lab.

Table of Contents

� Definition

� Array Representation

� Linked Representation

� Stack Applications� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Offline Equivalence Class Problem

� Rat in a Maze

Page 26: DS Ch 9 (1 unit) Stacks

Data Structures 26SNU

IDB Lab.

Parenthesis Matching

� Print out matching of the left and right parentheses in a character string� (a*(b+c)+d) : output � (0,10), (3,7) match� (a+b))(

� Output � (0, 4) match� Output � 5, 6 have no matching parentheses

� Solution steps� Scan the input expression from left to right� ‘ ( ‘ is encountered, add its position to the stack� ‘ ) ‘ is encountered, remove matching position from stack

� Complexity� Push / pop operations : O(n) time

Page 27: DS Ch 9 (1 unit) Stacks

Data Structures 27SNU

IDB Lab.

Example: Parenthesis Matching (1)

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0

‘(’ meet

top

Page 28: DS Ch 9 (1 unit) Stacks

Data Structures 28SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0top

skip

Example: Parenthesis Matching (2)

Page 29: DS Ch 9 (1 unit) Stacks

Data Structures 29SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0top

skip

Example: Parenthesis Matching (3)

Page 30: DS Ch 9 (1 unit) Stacks

Data Structures 30SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0

top

‘(‘ meet

3

Example: Parenthesis Matching (4)

Page 31: DS Ch 9 (1 unit) Stacks

Data Structures 31SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0

top

skip

3

Example: Parenthesis Matching (5)

Page 32: DS Ch 9 (1 unit) Stacks

Data Structures 32SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0

top

‘)’ meet

3

Example: Parenthesis Matching (6)

Page 33: DS Ch 9 (1 unit) Stacks

Data Structures 33SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0top

‘)’ meet

Example: Parenthesis Matching (7)

Output : (3, 7)

Page 34: DS Ch 9 (1 unit) Stacks

Data Structures 34SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0top

skip

Example: Parenthesis Matching (8)

Page 35: DS Ch 9 (1 unit) Stacks

Data Structures 35SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

0top

‘)’ meet

Example: Parenthesis Matching (9)

Page 36: DS Ch 9 (1 unit) Stacks

Data Structures 36SNU

IDB Lab.

� (a*(b+c)+d)

character

position

)d+)c+b(*a(

109876543210

‘)’ meet

Output : (3, 7), (0, 10)

Example: Parenthesis Matching (10)

Page 37: DS Ch 9 (1 unit) Stacks

Data Structures 37SNU

IDB Lab.

Parenthesis Matching Code

public static voidprintMatchedPairs(String expr) {

/* data members */

// scan expression expr for ( and )

for (int i = 0; i < length; i++)

if ( expr.charAt(i) == '(‘ ) s.push(new Integer(i));

else if (expr.charAt(i) == ')')

try{ // remove location of matching '(' from stack

System.out.println(s.pop() + " " + i); }

catch (Exception e) { // stack was empty, no match exists }

// remaining '(' in stack are unmatchedwhile (!s.empty())

System.out.println("No match for left parenthesis at " + s.pop());}

Page 38: DS Ch 9 (1 unit) Stacks

Data Structures 38SNU

IDB Lab.

Table of Contents

� Stack Applications

� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Switch Box Routing

� Offline Equivalence Class Problem

� Rat in a Maze

Page 39: DS Ch 9 (1 unit) Stacks

Data Structures 39SNU

IDB Lab.

Towers of Hanoi

� Mission: Move the disks from tower1 to tower2

� Each tower operates as a stack

� Cannot place a big disk on top of a smaller one� Move n-1 disks to tower3 using tower2� Move the largest to tower2� Move the n-1 disks from tower3 to tower2 using tower1

� Use of Recursion

Tower 1 Tower 2 Tower 3

Page 40: DS Ch 9 (1 unit) Stacks

Data Structures 40SNU

IDB Lab.

TOH Example (1/8)

� Mission: Move the disks from tower1 to tower2

321

Tower 1 Tower 2 Tower 3

Page 41: DS Ch 9 (1 unit) Stacks

Data Structures 41SNU

IDB Lab.

TOH Example (2/8)

� Mission: Move the disks from tower1 to tower2

32

Tower 1 Tower 2 Tower 3

1

Page 42: DS Ch 9 (1 unit) Stacks

Data Structures 42SNU

IDB Lab.

TOH Example (3/8)

� Mission: Move the disks from tower1 to tower2

3

Tower 1 Tower 2 Tower 3

1 2

Page 43: DS Ch 9 (1 unit) Stacks

Data Structures 43SNU

IDB Lab.

TOH Example (4/8)

� Mission: Move the disks from tower1 to tower2

3

Tower 1 Tower 2 Tower 3

12

Page 44: DS Ch 9 (1 unit) Stacks

Data Structures 44SNU

IDB Lab.

TOH Example (5/8)

� Mission: Move the disks from tower1 to tower2

Tower 1 Tower 2 Tower 3

123

Page 45: DS Ch 9 (1 unit) Stacks

Data Structures 45SNU

IDB Lab.

TOH Example (6/8)

� Mission: Move the disks from tower1 to tower2

Tower 1 Tower 2 Tower 3

1 23

Page 46: DS Ch 9 (1 unit) Stacks

Data Structures 46SNU

IDB Lab.

TOH Example (7/8)

� Mission: Move the disks from tower1 to tower2

Tower 1 Tower 2 Tower 3

123

Page 47: DS Ch 9 (1 unit) Stacks

Data Structures 47SNU

IDB Lab.

TOH Example (8/8)

� Mission: Move the disks from tower1 to tower2

Tower 1 Tower 2 Tower 3

123

Page 48: DS Ch 9 (1 unit) Stacks

Data Structures 48SNU

IDB Lab.

1st code: towersOfHanoi(m,1,2,3)

public static void towersOfHanoi(int n, int x, int y, int z)

{ // Move the top n disks from tower x to tower y.

// Use tower z for intermediate storage.

if (n > 0) {

towersOfHanoi(n-1, x, z, y);

System.out.println ("Move top disk from tower " + x + " to top of tower " + y);

towersOfHanoi(n-1, z, y, x);

}

}

Page 49: DS Ch 9 (1 unit) Stacks

Data Structures 49SNU

IDB Lab.

Actual execution

TOH(3, x, y, z)

TOH(2, x, z, y)

TOH(1, x, y, z): move 1 from x to y

: move 2 from x to z

TOH(1, y, z, x): move 1 from y to z

move 3 from x to y

TOH(2, z, y, x)

TOH(1, z, x, y): move 1 from z to x

: move 2 from z to y

TOH(1, x, y, z): move 1 from x to y

[

[

Page 50: DS Ch 9 (1 unit) Stacks

Data Structures 50SNU

IDB Lab.

Complexity: 1st TOH code

� The number of moves: moves(n)

� n = 0 : moves(n) = 0

� n > 0 : moves(n) = 2 * moves(n-1) + 1

� Therefore moves(n) = 2n –1

� Time Complexity : ⍬⍬⍬⍬(2n)

Page 51: DS Ch 9 (1 unit) Stacks

Data Structures 51SNU

IDB Lab.

2nd Code: TOH (1/3)

public class TowersOfHanoiShowingStates

{

// data member

// the towers are tower[1:3]

private static ArrayStack [] tower;

code for towersOfHanoitowersOfHanoitowersOfHanoitowersOfHanoi ( )( )( )( ) comes here;comes here;comes here;comes here;

code forcode forcode forcode for showTowerStatesshowTowerStatesshowTowerStatesshowTowerStates ( )( )( )( ) comes here;comes here;comes here;comes here;

}}}}

� The 1st TOH code gives only the disk-move sequence

� What if we want to store the actual state of the 3 towers (the disk order bottom to top) � use stacks!

Page 52: DS Ch 9 (1 unit) Stacks

Data Structures 52SNU

IDB Lab.

2nd code: TOH (2/3)

/** n disk Towers of Hanoi problem */public static void towersOfHanoi(int n) {

// create three stacks, tower[0] is not usedtower = new ArrayStack[4];for (int i = 1; i <= 3; i++)

tower[i] = new ArrayStack();

for (int d = n; d > 0; d--) tower[1].push(new Integer(d)); // add disk d to tower 1

// move n disks from tower 1 to 2 using 3 as intermediate towershowTowerStates(n, 1, 2, 3);

}

Page 53: DS Ch 9 (1 unit) Stacks

Data Structures 53SNU

IDB Lab.

2nd code: TOH (3/3)

public static void showTowerStates(int n, int x, int y, int z)

{ // Move the top n disks from tower x to tower y.

if (n > 0) {

showTowerStates(n-1, x, z, y);

Integer d = (Integer) tower[x].pop(); // move d from top of tower x

tower[y].push(d); // to top of tower ySystem.out.println

("Move disk " + d + " from tower "+ x + " to top of tower " + y);

showTowerStates(n-1, z, y, x);

}

}

Page 54: DS Ch 9 (1 unit) Stacks

Data Structures 54SNU

IDB Lab.

Table of Contents

� Stack Applications

� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Offline Equivalence Class Problem

� Rat in a Maze

Page 55: DS Ch 9 (1 unit) Stacks

Data Structures 55SNU

IDB Lab.

Rearranging Railroad Cars (1)� There are numbered N stations

� The freight train visits these stations in the order n through 1

� Must reorder the cars of the freight train to be in the order 1 through n from front to back

� Want to drop the x’th car into the station x and keep going

input track output track

H1 H2 H3

[581742963]

(a) Initial

H1 H2 H3

[987654321]

(b) FinalHow?

Page 56: DS Ch 9 (1 unit) Stacks

Data Structures 56SNU

IDB Lab.

Rearranging Railroad Cars (2)

� Solution steps

� If the car is the expected next one in the output track, move itdirectly to output track

� If not, move it to a holding track

� The holding tracks operate in a LIFO manner

� Assignment rule : The new car u is moved to the holding track H that has at its top a car with smallest label v such that v > u

� The bottom of each holding track has a big value

Page 57: DS Ch 9 (1 unit) Stacks

Data Structures 57SNU

IDB Lab.

Rearranging Railroad Cars (1/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

3 > 1So, move 3 to

holding track H1

Assume: the bottom of holding block has a big number v

Page 58: DS Ch 9 (1 unit) Stacks

Data Structures 58SNU

IDB Lab.

Rearranging Railroad Cars (2/17)

� Example : Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

6

6 > 1So, move 6 to holding

track H2 with the smallest label of its top v > 6

Page 59: DS Ch 9 (1 unit) Stacks

Data Structures 59SNU

IDB Lab.

Rearranging Railroad Cars (3/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

9

9 > 1So, move 9 to holding track H3 with the smallest label of

its top v > 9

6

Page 60: DS Ch 9 (1 unit) Stacks

Data Structures 60SNU

IDB Lab.

Rearranging Railroad Cars (4/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

2

2 > 1So, move 2 to holding

track H1 because 2 < 3 (hoding track with the

smallest label of its top)

6 9

Page 61: DS Ch 9 (1 unit) Stacks

Data Structures 61SNU

IDB Lab.

Rearranging Railroad Cars (5/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

4

4 > 1So, move 4 to holding track H2

because 4 < 6 (hoding track with the smallest label of its top)

6 9

2

Page 62: DS Ch 9 (1 unit) Stacks

Data Structures 62SNU

IDB Lab.

Rearranging Railroad Cars (6/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

7

7 > 1So, move 7 to holding

track H3 because 7 < 9 (holding track with the

smallest label of its top)

6 9

2 4

Page 63: DS Ch 9 (1 unit) Stacks

Data Structures 63SNU

IDB Lab.

Rearranging Railroad Cars (7/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

1

1

1= 1So, move 1 to output track

6 9

2 4 7

Page 64: DS Ch 9 (1 unit) Stacks

Data Structures 64SNU

IDB Lab.

Rearranging Railroad Cars (8/17)� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

2

6 9

4 71

2

2 = 2So, move 2 to output track

Page 65: DS Ch 9 (1 unit) Stacks

Data Structures 65SNU

IDB Lab.

Rearranging Railroad Cars (9/17)� Example : Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput

3

3

6 9

4 71

2

3 = 3So, move 3 to output track

Page 66: DS Ch 9 (1 unit) Stacks

Data Structures 66SNU

IDB Lab.

Rearranging Railroad Cars (10/17)

� Example : Input : 581742963

input trackoutput track

H1 H2 H3

(a) Initial

nextCarToOutput

3

4

6 9

4 7 12

4 = 4So, move 4 to output track

Page 67: DS Ch 9 (1 unit) Stacks

Data Structures 67SNU

IDB Lab.

Rearranging Railroad Cars (11/17)

� Example: Input : 581742963

input trackoutput track

H1 H2 H3

(a) Initial

nextCarToOutput 5

6 9

78

8 > 5So, move 8 to holding track H1(hoding track with the smallest

label of its top)

3

12

4

Page 68: DS Ch 9 (1 unit) Stacks

Data Structures 68SNU

IDB Lab.

Rearranging Railroad Cars (12/17)

� Example: Input : 581742963

input track output track

H1 H2 H3

(a) Initial

nextCarToOutput 5

6 9

75

5 = 5So, move 5 to output track

directly

8

3

12

4

Page 69: DS Ch 9 (1 unit) Stacks

Data Structures 69SNU

IDB Lab.

Rearranging Railroad Cars (13/17)

� Example: Input : 581742963

input trackoutput track

H1 H2 H3

(a) Initial

nextCarToOutput 6

6 9

7

83

12

45

6 = 6So, move 6 to output track

Page 70: DS Ch 9 (1 unit) Stacks

Data Structures 70SNU

IDB Lab.

Rearranging Railroad Cars (14/17)

� Example : Input : 581742963

input trackoutput track

H1 H2 H3

(a) Initial

nextCarToOutput 7

9

7

8

7 = 7So, move 7 to output track

3

12

456

Page 71: DS Ch 9 (1 unit) Stacks

Data Structures 71SNU

IDB Lab.

Rearranging Railroad Cars (15/17)

� Example: Input : 581742963

input trackoutput track

H1 H2 H3

(a) Initial

nextCarToOutput 8

98

8 = 8So, move 8 to output track

3

12

4567

Page 72: DS Ch 9 (1 unit) Stacks

Data Structures 72SNU

IDB Lab.

Rearranging Railroad Cars (16/17)

� Example: Input : 581742963

input track

output track

H1 H2 H3

(a) Initial

nextCarToOutput 9

9

9 = 9So, move 9 to output track

3

12

45678

Page 73: DS Ch 9 (1 unit) Stacks

Data Structures 73SNU

IDB Lab.

Rearranging Railroad Cars (17/17)

� Example: Input : 581742963

input track

output track

H1 H2 H3

(a) Initial

nextCarToOutput 9

3

12

456789

Page 74: DS Ch 9 (1 unit) Stacks

Data Structures 74SNU

IDB Lab.

RailRoadwithStacks (1)

Use array-based stackspublic class RailRoadWithStacks {// data members: ArrayStack[], inputOrder[], numOfCars, numOfTracks, smallestCar, itsTrack

//methods/* * rearrange railroad cars beginning with the initial order inputOrder[]railroad (int [] inputOrder, int NoOfCars, int NoOfTra cks)/* * output the smallest car from the holding tracks outputFromHoldingTrack () /* * put car c into a holding trackputInHoldingTrack (int c)}

Page 75: DS Ch 9 (1 unit) Stacks

Data Structures 75SNU

IDB Lab.

RailRoadwithStack (2)

public static public static public static public static booleanbooleanbooleanboolean railroadrailroadrailroadrailroad ((((intintintint [] [] [] [] inputOrderinputOrderinputOrderinputOrder, , , , intintintint NoOfCarsNoOfCarsNoOfCarsNoOfCars, , , , intintintint NoOfTracksNoOfTracksNoOfTracksNoOfTracks){ ){ ){ ){ numOfCarsnumOfCarsnumOfCarsnumOfCars = = = = NoOfCarsNoOfCarsNoOfCarsNoOfCars; ; ; ; numOfTracksnumOfTracksnumOfTracksnumOfTracks = = = = NoOfTracksNoOfTracksNoOfTracksNoOfTracks;;;;track = new track = new track = new track = new ArrayStackArrayStackArrayStackArrayStack [[[[numOfTracksnumOfTracksnumOfTracksnumOfTracks + 1];+ 1];+ 1];+ 1]; // create stacks as holding tracks// create stacks as holding tracks// create stacks as holding tracks// create stacks as holding tracksfor (for (for (for (intintintint i = 1; i <= i = 1; i <= i = 1; i <= i = 1; i <= numOfTracksnumOfTracksnumOfTracksnumOfTracks; i++) ; i++) ; i++) ; i++) track[itrack[itrack[itrack[i] = new ] = new ] = new ] = new ArrayStackArrayStackArrayStackArrayStack();();();();intintintint nextCarToOutputnextCarToOutputnextCarToOutputnextCarToOutput = 1; = 1; = 1; = 1; smallestCarsmallestCarsmallestCarsmallestCar = = = = numOfCarsnumOfCarsnumOfCarsnumOfCars + 1;+ 1;+ 1;+ 1; // no car in holding tracks// no car in holding tracks// no car in holding tracks// no car in holding tracks

for (for (for (for (intintintint i = 1; i <= i = 1; i <= i = 1; i <= i = 1; i <= numOfCarsnumOfCarsnumOfCarsnumOfCars; i++) {; i++) {; i++) {; i++) { // rearrange cars// rearrange cars// rearrange cars// rearrange carsif (if (if (if (inputOrder[iinputOrder[iinputOrder[iinputOrder[i] == ] == ] == ] == nextCarToOutputnextCarToOutputnextCarToOutputnextCarToOutput) ) ) ) {{{{ // send car to output track// send car to output track// send car to output track// send car to output track

nextCarToOutputnextCarToOutputnextCarToOutputnextCarToOutput++;++;++;++;

while (while (while (while (smallestCarsmallestCarsmallestCarsmallestCar == == == == nextCarToOutputnextCarToOutputnextCarToOutputnextCarToOutput){){){){ //output from holding tracks//output from holding tracks//output from holding tracks//output from holding tracks

outputFromHoldingTrackoutputFromHoldingTrackoutputFromHoldingTrackoutputFromHoldingTrack(); (); (); (); nextCarToOutputnextCarToOutputnextCarToOutputnextCarToOutput++;} ++;} ++;} ++;}

} } } } elseelseelseelse if ( !if ( !if ( !if ( !putInHoldingTrack(inputOrder[iputInHoldingTrack(inputOrder[iputInHoldingTrack(inputOrder[iputInHoldingTrack(inputOrder[i])])])]) )))) return false;return false;return false;return false;} } } } return true; return true; return true; return true;

}}}}

Page 76: DS Ch 9 (1 unit) Stacks

Data Structures 76SNU

IDB Lab.

� Move a car from a holding track to the output track

private static void outputFromHoldingTrack() {track[itsTrack].pop(); // remove smallestCar from itsTrack

// find new smallestCar and itsTrack by checking top of all stackssmallestCar = numOfCars + 2;for (int i = 1; i <= numOfTracks; i++)

if (!track[i].empty() && ((Integer) track[i].peek() ).intValue() < smallestCar) {smallestCar = ((Integer) track[i].peek()).intValue();itsTrack = i;

}}

RailRoadwithStack (3)

Page 77: DS Ch 9 (1 unit) Stacks

Data Structures 77SNU

IDB Lab.

� Put car c into a holding track using the assignment rule

private static booleanputInHoldingTrack(int c ) { // find best holding track for car cint bestTrack = 0int bestTop = numOfCars + 1; for (int i = 1; i <= numOfTracks; i++) { // scan tracks

if (!track[i].empty()) { // track i not emptyint topCar = ((Integer) track[i].peek()).intValue();if (c < topCar && topCar < bestTop){ // track i has smaller car at top

bestTop = topCar; bestTrack = i;}

} else if (bestTrack == 0) bestTrack = i; // track i empty}

if (bestTrack == 0) return false; // no feasible tracktrack[bestTrack].push(new Integer(c)); // add c to bestTrackif (c < smallestCar) { // update smallestCar and itsTrack if needed

smallestCar = c;itsTrack = bestTrack; }

return true;}

RailRoadwithStack (4)

Page 78: DS Ch 9 (1 unit) Stacks

Data Structures 78SNU

IDB Lab.

Complexity: RailRoadWithStack

� Complexity of RailRoad()� outputFromHoldingTrack() � O( numOfCars * numOfTracks )

� putInHoldingTrack() � O( numOfCars * numOfTracks )

� The rest of the code � ⍬⍬⍬⍬( numOfCars )

� The overall complexity � O( numOfCars * numOfTracks )

� If a balanced binary search tree is used for storing the labels of the cars at the top of the holding tracks, finding the holding track can be performed efficiently

� The complexity can be reduced totototo

O( numOfCars * log(numOfTracks) )

Page 79: DS Ch 9 (1 unit) Stacks

Data Structures 79SNU

IDB Lab.

Table of Contents

� Stack Applications

� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Offline Equivalence Class Problem

� Rat in a Maze

Page 80: DS Ch 9 (1 unit) Stacks

Data Structures 80SNU

IDB Lab.

Offline Equivalence Class Problem (1)

� Problem� Input :

� the number of element: n� the number of relation pairs: r� the r relation pairs

� Output : partition the n elements into equivalence classes

� ExampleExampleExampleExample� N=9, r=11N=9, r=11N=9, r=11N=9, r=11� R = 11 relation pairsR = 11 relation pairsR = 11 relation pairsR = 11 relation pairs

{ (1,5), (1,6), (3,7), (4,8), (5,2), (6,5), (4,9), (9,7), (7,8), (3,4), (6,2) }

Page 81: DS Ch 9 (1 unit) Stacks

Data Structures 81SNU

IDB Lab.

Offline Equivalence Class Problem (2)

� Solution Strategy

� The 1st phase : Input the data and set up n lists to represent the relation pairs

� Each relation pair(i,j), i is put on list[j] and j is put on list[i] :

{ (1,5), (1,6), (3,7), (4,8), (5,2),(6,5),

(4,9), (9,7), (7,8), (3,4), (6,2) }

list[1] = [5, 6], list[2] = [5, 6], list[3] = [7, 4],

list[4] = [8, 9, 3], list[5] = [1, 2, 6], list[6] = [1, 2, 5],

list[7] = [3, 9, 8], list[8] = [4, 7], list[9] = [4, 7]

Page 82: DS Ch 9 (1 unit) Stacks

Data Structures 82SNU

IDB Lab.

Offline Equivalence Class Problem (3)

� The 2nd phase : The equv classes(EC) are identified by locating a seed

1. Find a seed that is output as the first member of the next EC

2. The seed is put onto a list, unprocessedList (Stack), of elements that are in the same EC

3. Remove an element i from unprocessedList

4. Output and add to unprocessedList elements on list[i]

that haven’t already been identified as class members

5. Until the unprocessedList becomes empty, Continues the process 3&4.

- If it is empty, we have completed a class

6. Proceed to find a seed for the next class

Page 83: DS Ch 9 (1 unit) Stacks

Data Structures 83SNU

IDB Lab.

Equivalence Class with Stack (1)

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New class

1

unprocessedList(stack)

1

1

output add

Page 84: DS Ch 9 (1 unit) Stacks

Data Structures 84SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1 1

list[1] = 5 6

Equivalence Class with Stack (2)

Page 85: DS Ch 9 (1 unit) Stacks

Data Structures 85SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1 1

output list[1] = 5 6

5 6

If they already have been output, ignore them

Equivalence Class with Stack (3)

Page 86: DS Ch 9 (1 unit) Stacks

Data Structures 86SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output add

5 6

5

6 5

6

Equivalence Class with Stack (4)

Page 87: DS Ch 9 (1 unit) Stacks

Data Structures 87SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1 5

6

6

5

list[5] = 1 2

6

Equivalence Class with Stack (5)

Page 88: DS Ch 9 (1 unit) Stacks

Data Structures 88SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output

5

6

6

5

list[5] = 1 2

6

1 2

6

1,6 already have been output, so ignore 1,6 and output 2

Equivalence Class with Stack (6)

Page 89: DS Ch 9 (1 unit) Stacks

Data Structures 89SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output

5

6

6

1

2

6

add

22

Equivalence Class with Stack (7)

Page 90: DS Ch 9 (1 unit) Stacks

Data Structures 90SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output

5

6

6

add

2

2

list[2] = 5 6

5 6

If 5,6 already have been output, ignore them

Equivalence Class with Stack (8)

Page 91: DS Ch 9 (1 unit) Stacks

Data Structures 91SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output

5

6

6

add

2

list[6] = 1 2

5

1 2

5

1,2,5 already have been output, ignore them

Equivalence Class with Stack (9)

Page 92: DS Ch 9 (1 unit) Stacks

Data Structures 92SNU

IDB Lab.

list[1]=[5,6]list[2]=[5,6]list[3]=[7,4]list[4]=[8,9,3]list[5]=[1,2,6]list[6]=[1,2,5]list[7]=[3,9,8]list[8]=[4,7]list[9]=[4,7]

seed

New classunprocessedList

(stack)

1

output

5

6

add

2

This is empty, so we find one equivalence class{1,2,5,6}

By this way, we can find another class{3,4,7,8,9}

Equivalence Class with Stack (10)

Page 93: DS Ch 9 (1 unit) Stacks

Data Structures 93SNU

IDB Lab.

� Operations

� Insert and examine all elements

� Select a representation for list and unprocessedList� Space requirement

� Between 2r (stack) and 4r (linked list) references

� Time performance

� The linked implementations are slower than array-based counterparts.

� So, unprocessedList and list is implemented as an ArrayStack

Equivalence Class with Stack: Code (1)

Page 94: DS Ch 9 (1 unit) Stacks

Data Structures 94SNU

IDB Lab.

public static void main (String [] args) {// input the number of elements, n// input the number of relations, r // create an array of empty stacks, list[0] not usedArrayStack [] list = new ArrayStack [n + 1];for (int i = 1; i <= n; i++) list[i] = new ArrayS tack();

for (int i = 1; i <= r; i++) { // input the r relations and put on stacks

int a = keyboard.readInteger();

int b = keyboard.readInteger();

list[a].push(new Integer(b));

list[b].push(new Integer(a)); }

// initialize to output equivalence classes

ArrayStack unprocessedList = new ArrayStack();

boolean [] out = new boolean [n + 1];

Equivalence Class with Stack: Code (1)

Page 95: DS Ch 9 (1 unit) Stacks

Data Structures 95SNU

IDB Lab.

for (int i = 1; i <= n; i++) // output equivalence classesif (!out[i]) { // start of a new class

out[i] = true;

unprocessedList.push(new Integer(i)) ;while (!unprocessedList.empty()) { // get rest of class from unprocessedList

int j = ((Integer) unprocessedList.pop()).intValue();while (!list[j].empty()) { // elements on list[j] are in the same class

int q = ((Integer) list[j].pop()).intValue();

if (!out[q]) { // q not yet output

System.out.print(q + " ");

out[q] = true;

unprocessedList.push(new Integer(q)); } //end of if

} //end of while

} //end of while

} //end of if

} // end of main

Equivalence Class with Stack: Code (2)

Page 96: DS Ch 9 (1 unit) Stacks

Data Structures 96SNU

IDB Lab.

Complexity: Equv Class with Stack

� Input and initialize the array list[]

� O(n+r)

� Pop and examine all elements

� ⍬⍬⍬⍬(r)

� So, overall complexity

� O(n+r)

� If no exception, ⍬⍬⍬⍬(n+r)

Page 97: DS Ch 9 (1 unit) Stacks

Data Structures 97SNU

IDB Lab.

Table of Contents

� Stack Applications

� Parenthesis Matching

� Towers of Hanoi

� Rearranging Railroad Cars

� Offline Equivalence Class Problem

� Rat in a Maze

Page 98: DS Ch 9 (1 unit) Stacks

Data Structures 98SNU

IDB Lab.

Rat in a Maze: Problem

� What is maze? � A rectangular area with an entrance and an exit

� The interior of maze contains obstacles

� Suppose that maze is to be modeled as an n x m matrix� Position (1, 1) : entrance

� Position (n, m) : exit

� Each maze position : row and column intersection

� Position (i, j) = 1 iff there is an obstacle

� Position (i, j) = 0 otherwise

� Problem � Find a path from the entrance to the exit of a maze

� A path is a sequence of position

Page 99: DS Ch 9 (1 unit) Stacks

Data Structures 99SNU

IDB Lab.

Rat in a Maze: Representation

� Example

(a) A maze (b) Matrix representation of maze

Page 100: DS Ch 9 (1 unit) Stacks

Data Structures 100SNU

IDB Lab.

Find a path: Idea{ Begin with the entrance

If (the present position is the exit) { pop the all entries in the path stack;

return }Else { We block the current position;

If (the current position is surrounded by the obstacles) { pop the stack; back-up }

While ( there is unblocked adjacent maze position ) { Move to this new adjacent position;

Push the current position into the path stack;Attempt to find a path }

If ( tried all adjacent unblocked positions and no path is found ) { There is no path in maze;

return }

}

Page 101: DS Ch 9 (1 unit) Stacks

Data Structures 101SNU

IDB Lab.

Rat in a Maze: Strategy (1)

� Maze� Storing 1 or 0

� 2D array of type byte or 2D array of type Boolean

� Each maze position : Position(i,j) � maze[i][j]� Use objects of type Position, which is defined a class with private

members row and col

� Path : � Use array-based stack that maintains the path from entrance to

the current position

Page 102: DS Ch 9 (1 unit) Stacks

Data Structures 102SNU

IDB Lab.

Rat in a Maze: Strategy (2)

� Four moves are possible: right, down, left, up� To avoid to handle positions on the boundaries of maze differently

from interior positions

� Surround the maze with a wall of obstacles.� For an m x m maze, 0th row & m+1th row and 0th cloumn & m+1th

column are added

� see figure 9.15 (page 343)

� Theoretically a long path passes m x m positions (worst case) while a short path passes 2m positions (best case) in a maze with no blockages

Page 103: DS Ch 9 (1 unit) Stacks

Data Structures 103SNU

IDB Lab.

Rat in a Maze: Strategy (3)� Have to select the order of moves from “here”

� For example, move right, then down, then left, and up� The coordinates to move to are computed by maintaining a table of offsets.

� To avoid moving to positions that we have been through before � we place an obstacle on a visited position, i.e, set maze[i][j] =1

� If we have to back up, the next move option is computed by the followings:if (next.row == here.row) option = 2 + next.col – here.col;else option = 3 + next.row – here.row;

Page 104: DS Ch 9 (1 unit) Stacks

Data Structures 104SNU

IDB Lab.

Rat In a Maze: Example (1)� Maze M[3,3]Maze M[3,3]Maze M[3,3]Maze M[3,3]

� 0 0 10 0 10 0 10 0 1

� 0 1 00 1 00 1 00 1 0

� 0 0 00 0 00 0 00 0 0

� StartStartStartStart: M[1,1] =1, here = M[1,1]: M[1,1] =1, here = M[1,1]: M[1,1] =1, here = M[1,1]: M[1,1] =1, here = M[1,1]

� Move to M[1,2]Move to M[1,2]Move to M[1,2]Move to M[1,2] : : : : pushStackpushStackpushStackpushStack M[1,1], here=M[1,2], blocking M[1,2]M[1,1], here=M[1,2], blocking M[1,2]M[1,1], here=M[1,2], blocking M[1,2]M[1,1], here=M[1,2], blocking M[1,2]

� M[1,2] is surrounded by M[1,2] is surrounded by M[1,2] is surrounded by M[1,2] is surrounded by “ 1111” ���� BackBackBackBack----up: up: up: up: popStackpopStackpopStackpopStack, next = M[1,1] , next = M[1,1] , next = M[1,1] , next = M[1,1] ���� option = 2 + option = 2 + option = 2 + option = 2 + next.colnext.colnext.colnext.col – here.colhere.colhere.colhere.col = 1, here = next = M[1,1]= 1, here = next = M[1,1]= 1, here = next = M[1,1]= 1, here = next = M[1,1]

� Move to M[2,1]Move to M[2,1]Move to M[2,1]Move to M[2,1] : : : : pushStackpushStackpushStackpushStack M[1,1], here=M[2,1], blocking M[2,1]M[1,1], here=M[2,1], blocking M[2,1]M[1,1], here=M[2,1], blocking M[2,1]M[1,1], here=M[2,1], blocking M[2,1]

Page 105: DS Ch 9 (1 unit) Stacks

Data Structures 105SNU

IDB Lab.

Rat In a Maze: Example (2)� Maze M[3,3]Maze M[3,3]Maze M[3,3]Maze M[3,3]

� 1 11 11 11 1 1111

� 1111 1 01 01 01 0

� 0 0 00 0 00 0 00 0 0

� Move to M[3,1]Move to M[3,1]Move to M[3,1]Move to M[3,1] : : : : pushStackpushStackpushStackpushStack M[2,1], here=M[3,1], blocking M[3,1]M[2,1], here=M[3,1], blocking M[3,1]M[2,1], here=M[3,1], blocking M[3,1]M[2,1], here=M[3,1], blocking M[3,1]

� Move to M[3,2]Move to M[3,2]Move to M[3,2]Move to M[3,2] : : : : pushStackpushStackpushStackpushStack M[3,1], here=M[3,2], blocking M[3,2]M[3,1], here=M[3,2], blocking M[3,2]M[3,1], here=M[3,2], blocking M[3,2]M[3,1], here=M[3,2], blocking M[3,2]

� Move to M[3,3]Move to M[3,3]Move to M[3,3]Move to M[3,3] : : : : pushStackpushStackpushStackpushStack M[3,2], here=M[3,3], blocking M[3,3] M[3,2], here=M[3,3], blocking M[3,3] M[3,2], here=M[3,3], blocking M[3,3] M[3,2], here=M[3,3], blocking M[3,3]

� You arrived at the entrance: You arrived at the entrance: You arrived at the entrance: You arrived at the entrance: pushStackpushStackpushStackpushStack M[3,3] M[3,3] M[3,3] M[3,3]

� Pop all the entries from the stack & print in a reverse order:Pop all the entries from the stack & print in a reverse order:Pop all the entries from the stack & print in a reverse order:Pop all the entries from the stack & print in a reverse order:

M[1,1],M[1,1],M[1,1],M[1,1], M[2,1], M[3,1], M[3,2], M[3,3]M[2,1], M[3,1], M[3,2], M[3,3]M[2,1], M[3,1], M[3,2], M[3,3]M[2,1], M[3,1], M[3,2], M[3,3]

� return true;return true;return true;return true;

Page 106: DS Ch 9 (1 unit) Stacks

Data Structures 106SNU

IDB Lab.

Rat in a Maze: Main()

//private static method welcome//private static method inputMaze//private static method findPath//private static method outputPath

public static void main(String[] args){welcome();inputMaze();if (findPath())

outputPath();else System.out.println(“No path”);

}

Page 107: DS Ch 9 (1 unit) Stacks

Data Structures 107SNU

IDB Lab.

FindPath() code using stack (1)private static private static private static private static booleanbooleanbooleanboolean findPathfindPathfindPathfindPath(){(){(){(){

path = path = path = path = newnewnewnew ArrayStackArrayStackArrayStackArrayStack(); (); (); (); // initialize offsets// initialize offsets// initialize offsets// initialize offsetsPosition [] offset = Position [] offset = Position [] offset = Position [] offset = newnewnewnew Position [4];Position [4];Position [4];Position [4];offset[0] = offset[0] = offset[0] = offset[0] = newnewnewnew Position(0, 1); Position(0, 1); Position(0, 1); Position(0, 1); // right// right// right// rightoffset[1] =offset[1] =offset[1] =offset[1] = newnewnewnew Position(1, 0); Position(1, 0); Position(1, 0); Position(1, 0); // down// down// down// downoffset[2] = offset[2] = offset[2] = offset[2] = newnewnewnew Position(0, Position(0, Position(0, Position(0, ----1); 1); 1); 1); // left// left// left// leftoffset[3] = offset[3] = offset[3] = offset[3] = newnewnewnew Position(Position(Position(Position(----1, 0); 1, 0); 1, 0); 1, 0); // up// up// up// up

// initialize wall of obstacles around maze// initialize wall of obstacles around maze// initialize wall of obstacles around maze// initialize wall of obstacles around mazeforforforfor ((((intintintint i = 0; i <= size + 1; i++) {i = 0; i <= size + 1; i++) {i = 0; i <= size + 1; i++) {i = 0; i <= size + 1; i++) {

maze[0][i] = maze[0][i] = maze[0][i] = maze[0][i] = maze[sizemaze[sizemaze[sizemaze[size + 1][i] = 1; + 1][i] = 1; + 1][i] = 1; + 1][i] = 1; // bottom and top// bottom and top// bottom and top// bottom and topmaze[i][0] = maze[i][0] = maze[i][0] = maze[i][0] = maze[i][sizemaze[i][sizemaze[i][sizemaze[i][size + 1] = 1; + 1] = 1; + 1] = 1; + 1] = 1; // left and right// left and right// left and right// left and right

}}}}Position here = Position here = Position here = Position here = newnewnewnew Position(1, 1);Position(1, 1);Position(1, 1);Position(1, 1);maze[1][1] = 1; maze[1][1] = 1; maze[1][1] = 1; maze[1][1] = 1; // prevent return to entrance// prevent return to entrance// prevent return to entrance// prevent return to entranceintintintint option = 0; option = 0; option = 0; option = 0; // next move// next move// next move// next moveintintintint lastOptionlastOptionlastOptionlastOption = 3; = 3; = 3; = 3;

Page 108: DS Ch 9 (1 unit) Stacks

Data Structures 108SNU

IDB Lab.

FindPath() code using stack (2)// search for a path// search for a path// search for a path// search for a pathwhile (while (while (while (here.rowhere.rowhere.rowhere.row != size || != size || != size || != size || here.colhere.colhere.colhere.col != size) { != size) { != size) { != size) { // not at exit // find a neighbor to move to// not at exit // find a neighbor to move to// not at exit // find a neighbor to move to// not at exit // find a neighbor to move to

intintintint r = 0, c = 0; r = 0, c = 0; r = 0, c = 0; r = 0, c = 0; // row and column of neighbor// row and column of neighbor// row and column of neighbor// row and column of neighborwhile (option <= while (option <= while (option <= while (option <= lastOptionlastOptionlastOptionlastOption) {) {) {) {

r = r = r = r = here.rowhere.rowhere.rowhere.row + + + + offset[option].rowoffset[option].rowoffset[option].rowoffset[option].row;;;;c = c = c = c = here.colhere.colhere.colhere.col + + + + offset[option].coloffset[option].coloffset[option].coloffset[option].col; ; ; ; if (if (if (if (maze[r][cmaze[r][cmaze[r][cmaze[r][c] == 0) break; ] == 0) break; ] == 0) break; ] == 0) break; // find a // find a // find a // find a neightborneightborneightborneightbor to proceed!to proceed!to proceed!to proceed!option++;option++;option++;option++; // next option // next option // next option // next option }}}}

// was a neighbor found?// was a neighbor found?// was a neighbor found?// was a neighbor found?if (option <= if (option <= if (option <= if (option <= lastOptionlastOptionlastOptionlastOption) { ) { ) { ) { // move to // move to // move to // move to maze[r][cmaze[r][cmaze[r][cmaze[r][c]]]]

path.push(herepath.push(herepath.push(herepath.push(here););););here = new here = new here = new here = new Position(rPosition(rPosition(rPosition(r, c);, c);, c);, c);maze[r][cmaze[r][cmaze[r][cmaze[r][c] = 1; ] = 1; ] = 1; ] = 1; // set to 1 to prevent revisit// set to 1 to prevent revisit// set to 1 to prevent revisit// set to 1 to prevent revisitoption = 0; }option = 0; }option = 0; }option = 0; }

elseelseelseelse { { { { // no neighbor to move to, back up// no neighbor to move to, back up// no neighbor to move to, back up// no neighbor to move to, back upif (if (if (if (path.emptypath.emptypath.emptypath.empty()) return false; ()) return false; ()) return false; ()) return false; // no place to back up to // no place to back up to // no place to back up to // no place to back up to Position next = (Position) Position next = (Position) Position next = (Position) Position next = (Position) path.poppath.poppath.poppath.pop();();();();if (if (if (if (next.rownext.rownext.rownext.row == == == == here.rowhere.rowhere.rowhere.row) option = 2 + ) option = 2 + ) option = 2 + ) option = 2 + next.colnext.colnext.colnext.col ---- here.colhere.colhere.colhere.col;;;;else option = 3else option = 3else option = 3else option = 3 + + + + next.rownext.rownext.rownext.row ---- here.rowhere.rowhere.rowhere.row;;;;here = next; } here = next; } here = next; } here = next; } //end of else //end of else //end of else //end of else

}}}} return true; return true; return true; return true; // at exit // at exit // at exit // at exit }}}}

Page 109: DS Ch 9 (1 unit) Stacks

Data Structures 109SNU

IDB Lab.

Complexity: Rat in a Maze

� Complexity

� For the time complexity, we move to each unblocked position of the input maze in worst case

� O(unblocked), where unblocked is the number of unblocked positions in the input maze

� Once we visited a position, we block it � no revisit

� That is, in m *m maze, the worst case of time complexity is O(size2) = O(m2)

Page 110: DS Ch 9 (1 unit) Stacks

Data Structures 110SNU

IDB Lab.

Summary� Stack is

� A kind of Linear list� Insertion and removal from one end “top”� LIFO(last-in-first-out) structure

� Representation� ArrayStack class� LinkedStack class

� Stack Applications� Parenthesis Matching� Towers of Hanoi� Rearranging Railroad Cars� Offline Equivalence Class Problem� Rat in a Maze