CSE/IT 213 - Graphs: New Mexico Tech
CSE/IT 213 - Graphs: New Mexico Tech
Stacks - a review
import java.util.*;
class Stack<T> implements StackInterface<T> {
private ArrayList<T> stack;
//constructors
/** default of ArrayList is 10 items */
public Stack() {
3
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);
}
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
...
...
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
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
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 this.numItems;
}
}