You are on page 1of 27

CSE/IT 213 - Graphs

New Mexico Tech


October 12, 2011

Stacks - a review

public interface StackInterface<T> {


/** True if stack is empty. */
boolean isEmpty ();
/** how many items in the stack. */
int size ();
/** get the top item in the stack but do not remove it */
T getTop ();
/** Remove and return the top item of the stack */
T pop ();
/** Add an item to the top of the stack */
2

void push (T x);


/** Get the index of the most-recently inserted item */
int lastIndexOf (T x);
}

How to implement Stack?


Use an ArrayList to provide the storage for a Stack.
This allows us to use ArrayLists methods.

import java.util.*;
class Stack<T> implements StackInterface<T> {
private ArrayList<T> stack;
//constructors
/** default of ArrayList is 10 items */
public Stack() {
3

stack = new ArrayList<T>();


}
public Stack(int initSizeOfStack) {
stack = new ArrayList<T>(initSizeOfStack);
}
//methods
public boolean isEmpty () {
return stack.isEmpty(); //true if no elements
}
public int size () {
return stack.size();
}

public T getTop () {
if (!stack.isEmpty())
return stack.get(stack.size() - 1);
else
return null;
}
public T pop () {
if (stack.isEmpty()) //stack contains no elements
return null;
return stack.remove(stack.size() - 1);
}

public void push(T x) {


stack.add(x); //using ArrayList methods
}
public int lastIndexOf (T x) {
return stack.lastIndexOf(x);
}
}

Graphs
A graph is a collection of vertices and edges.
Vertices, also called nodes, can have names and other
properties,
Edges are connections between two vertices.

Representing Graphs
First step is convert vertex names to an integer between
1 and n, where n is the number of vertices. Allows you
to use an array indexing to access vertices.
Then can use an adjacency matrix to represent a graph.
An adjacency matrix is a n n boolean valued matrix.
Where a[i][j] = 1 represents that there is an edge between vertex i and vertex j. a[j][i] is also assigned a 1.
While this adds to storage, makes algorithms easier.
Often assume that there is an edge from each vertex
to itself. So a[i][i] = 1. That is the diagonal of the
matrix is set to 1. In other cases, it may be easier to
assign 0 to the diagonal.
5

Adjacency Matrix
What is the graph of this adjacency matrix?

...

A
1

B 1

...

C
..

0
..

1
..

1
..

...
...

0
..

Z 1

...

...

The Lady or the Tiger?


A take on a short story published in 1884.
You have a house full of N rooms, connected by doors.
You can get to every room in the house through the
doors. Some rooms have multiple doors. A prisoner is
blindfolded and led into a random room in the house.
You have randomly placed a lady in one of the rooms
and have randomly placed a tiger in another. The blindfold is removed and the prisoner must search the rooms
one by one. If he finds the Lady he is freed and lives
happily ever after; otherwise if he finds the tiger, he
is....
7

The house can be modelled with a graph. Vertices are


the rooms. Door are edges. The house is connected
there is a path to every room (vertex). Use an adjacency matrix to represent connections.
How can we model the systematic search of rooms by
the prisoner? Use a stack to keep track of where he is
and keep track of visited rooms.
The prisoner can only visit a room once, but he may
backtrack through a previously visited room.

Lady or Tiger Algorithm


MARK initial room as visited
PUSH initial room onto the stack (represents rooms)
//the room at the top of stack is the room
//currently occupied by the prisoner
//the stack remembers previously visited rooms

WHILE (Lady AND Tiger are Undiscovered)


IF there is an unvisited room, r, adjacent to the room
on top of the stack (the current room)
visit r and mark r as visited
IF the lady or tiger is in r
the search is over
ELSE
push r onto stack
//move prisoner to room r
ELSE IF there is no unvisited room adjacent to room
on top of stack
pop the stack //backtrack to previous room
//the most recently visited room is now on top of stack
9

Depth-First Search
If you remove the lady and the tiger, you have a what
is called a Depth-First Search (DFS)
Can be used to see if a graph is connected. Once the
DFS stops check to see if all nodes were visited.

10

Queues
A First-in, First-out (FIFO) List
What is queue-ness?
What are the basic operations of a queue?

11

public interface QueueInterface<E>


{
/** inserts x at rear of queue */
public void insert(E x);
/** removes and returns front item
returns null if queue is empty */
public E remove();
/** returns true if no elements are in the queue */
public boolean isEmpty();
/** return the front item, but does not alter queue
returns null if the queue is empty */
public E peek();
12

/** returns the number if items in the queue */


public int size();
}

Queue Implementation
Implementation problem using ArrayList<T> for a queue.
A stack justs adds or removes at the end of the list.
ArrayList is efficient at doing this.
Queues though require that we remove the first element
of the ArrayList. When an element is removed from an
ArrayList, all elements are shifted. That is, element 1
is moved to position 0, element 2 moved to position 1,
etc. This is expensive.
The way around this is to use an array with two indices.
One that keeps track of the first element and one that
13

keeps track of the last element. Instead of moving


items when the first element is removed you just move
the index. The indices will circle around the array, a
circular buffer. Have to worry about overfilling array.
How do you implement circular buffers?

public class Queue<E> implements QueueInterface<E>{


private E[] queue;
private int numItems; //number of items in currently in queue
private int front, rear; //indices
private int maxQueue; //max capacity of queue
public Queue() {
queue = (E[]) new Object[10]; //new E[10]; doesnt work
//cannot create arrays of generic type
this.numItems = 0;
this.front = this.rear = -1; //-1 indicates queue is empty
this.maxQueue = 10;
}
14

public Queue(int max) {


this.maxQueue = max;
this.queue = (E[]) new Object[maxQueue];
this.numItems = 0;
this.front = this.rear = -1;
}

/** inserts x at rear of queue */


public void insert(E x) {
if (numItems == maxQueue) //queue is full
{
System.out.println("Queue Overflow");

System.exit(0);
}
this.rear = (this.rear + 1) % this.maxQueue;
this.queue[this.rear] = x;
this.numItems++;
if (this.numItems == 1)
this.front = this.rear;
}
/** removes and returns front item
returns null if queue is empty */
public E remove() {
if (this.numItems == 0)

return null; //return the void reference


E temp = this.queue[this.front];
numItems--;
if(numItems == 0)
this.front = this.rear = -1; //reset to init state
else
this.front = (this.front + 1) % this.maxQueue;
return temp;
}
/** returns true if no elements are in the queue */
public boolean isEmpty() {

return (this.numItems == 0);


}
/** return the front item, but does not alter queue
returns null if the queue is empty */
public E peek() {
if (this.numItems == 0)
return null;
else
return this.queue[this.front];
}
/** returns the number if items in the queue */
public int size() {

return this.numItems;
}
}

You might also like