2 Star 0 Fork 0

CS-IMIS-23 / 20172309_javaProgramming

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Graph.java 23.89 KB
一键复制 编辑 原始数据 按行查看 历史
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
package second_term.fifteenth_chapter;
import second_term.first_week.StackADT;
import second_term.second_week.LinkedStack;
import second_term.sixth_chapter.UnorderedListADT;
import second_term.sixth_chapter.UnorderedListArrayList;
import second_term.third_week.LinkedQueue;
import second_term.third_week.QueueADT;
import java.util.*;
/**
* Graph represents an adjacency matrix implementation of a graph.
*
* @author Lewis and Chase
* @version 4.0
*/
public class Graph<T> implements GraphADT<T>
{
protected final int DEFAULT_CAPACITY = 5;
protected int numVertices; // number of vertices in the graph
protected boolean[][] adjMatrix; // adjacency matrix
protected T[] vertices; // values of vertices
protected int modCount;
/**
* Creates an empty graph.
*/
public Graph()
{
numVertices = 0;
this.adjMatrix = new boolean[DEFAULT_CAPACITY][DEFAULT_CAPACITY];
this.vertices = (T[])(new Object[DEFAULT_CAPACITY]);
}
/**
* Returns a string representation of the adjacency matrix.
*
* @return a string representation of the adjacency matrix
*/
public String toString()
{
if (numVertices == 0)
return "Graph is empty";
String result = new String("");
result += "Adjacency Matrix\n";
result += "----------------\n";
result += "index\t";
for (int i = 0; i < numVertices; i++)
{
result += "" + i;
if (i < 10)
result += " ";
}
result += "\n\n";
for (int i = 0; i < numVertices; i++)
{
result += "" + i + "\t";
for (int j = 0; j < numVertices; j++)
{
if (adjMatrix[i][j])
result += "1 ";
else
result += "0 ";
}
result += "\n";
}
result += "\n\nVertex Values";
result += "\n-------------\n";
result += "index\tvalue\n\n";
for (int i = 0; i < numVertices; i++)
{
result += "" + i + "\t";
result += vertices[i].toString() + "\n";
}
result += "\n";
return result;
}
/**
* Inserts an edge between two vertices of the graph.
*
* @param index1 the first index
* @param index2 the second index
*/
public void addEdge(int index1, int index2)
{
if (indexIsValid(index1) && indexIsValid(index2))
{
adjMatrix[index1][index2] = true;
adjMatrix[index2][index1] = true;
modCount++;
}
}
/**
* Removes an edge between two vertices of the graph.
*
* @param index1 the first index
* @param index2 the second index
*/
public void removeEdge(int index1, int index2)
{
if (indexIsValid(index1) && indexIsValid(index2))
{
adjMatrix[index1][index2] = false;
adjMatrix[index2][index1] = false;
modCount++;
}
}
/**
* Inserts an edge between two vertices of the graph.
*
* @param vertex1 the first vertex
* @param vertex2 the second vertex
*/
public void addEdge(T vertex1, T vertex2)
{
addEdge(getIndex(vertex1), getIndex(vertex2));
}
/**
* Removes an edge between two vertices of the graph.
*
* @param vertex1 the first vertex
* @param vertex2 the second vertex
*/
public void removeEdge(T vertex1, T vertex2)
{
int index1 = getIndex(vertex1);
int index2 = getIndex(vertex2);
if (indexIsValid(index1) && indexIsValid(index2))
{
adjMatrix[index1][index2] = false;
adjMatrix[index2][index1] = false;
modCount++;
}
}
/**
* Adds a vertex to the graph, expanding the capacity of the graph
* if necessary.
*/
public void addVertex()
{
// To be completed as a Programming Project
}
/**
* Adds a vertex to the graph, expanding the capacity of the graph
* if necessary. It also associates an object with the vertex.
*
* @param vertex the vertex to add to the graph
*/
public void addVertex(T vertex)
{
if ((numVertices + 1) == adjMatrix.length)
expandCapacity();
vertices[numVertices] = vertex;
for (int i = 0; i < numVertices; i++)
{
adjMatrix[numVertices][i] = false;
adjMatrix[i][numVertices] = false;
}
numVertices++;
modCount++;
}
/**
* Removes a vertex at the given index from the graph. Note that
* this may affect the index values of other vertices.
*
* @param index the index at which the vertex is to be removed from
*/
public void removeVertex(int index)
{
if (indexIsValid(index)){
for (int j = index;j<numVertices-1;j++)
{
vertices[j] = vertices[j+1];
}
vertices[numVertices-1] = null;
for (int i = index; i < numVertices-1; i++)
{
for (int x=0;x<numVertices;x++)
adjMatrix[i][x] = adjMatrix[i+1][x];
}
for (int i = index; i < numVertices; i++)
{
for (int x=0;x<numVertices;x++)
adjMatrix[x][i] = adjMatrix[x][i+1];
}
for (int i = 0; i < numVertices; i++)
{
adjMatrix[numVertices][i] = false;
adjMatrix[i][numVertices] = false;
}
numVertices--;
modCount++;
}
}
/**
* Removes a single vertex with the given value from the graph.
*
* @param vertex the vertex to be removed from the graph
*/
public void removeVertex(T vertex)
{
removeVertex(getIndex(vertex));
}
/**
* Returns an iterator that performs a depth first traversal
* starting at the given index.
*
* @param startIndex the index from which to begin the traversal
* @return an iterator that performs a depth first traversal
*/
public Iterator<T> iteratorDFS(int startIndex)
{
Integer x;
boolean found;
StackADT<Integer> traversalStack = new LinkedStack<Integer>();
UnorderedListADT<T> resultList = new UnorderedListArrayList<T>();
boolean[] visited = new boolean[numVertices];
if (!indexIsValid(startIndex))
return resultList.iterator();
for (int i = 0; i < numVertices; i++)
visited[i] = false;
traversalStack.push(new Integer(startIndex));
resultList.addToRear(vertices[startIndex]);
visited[startIndex] = true;
while (!traversalStack.isEmpty())
{
x = traversalStack.peek();
found = false;
//Find a vertex adjacent to x that has not been visited
// and push it on the stack
for (int i = 0; (i < numVertices) && !found; i++)
{
if (adjMatrix[x.intValue()][i] && !visited[i])
{
traversalStack.push(new Integer(i));
resultList.addToRear(vertices[i]);
visited[i] = true;
found = true;
}
}
if (!found && !traversalStack.isEmpty())
traversalStack.pop();
}
return new GraphIterator(resultList.iterator());
}
/**
* Returns an iterator that performs a depth first search
* traversal starting at the given vertex.
*
* @param startVertex the vertex to begin the search from
* @return an iterator that performs a depth first traversal
*/
public Iterator<T> iteratorDFS(T startVertex)
{
return iteratorDFS(getIndex(startVertex));
}
/**
* Returns an iterator that performs a breadth first
* traversal starting at the given index.
*
* @param startIndex the index from which to begin the traversal
* @return an iterator that performs a breadth first traversal
*/
public Iterator<T> iteratorBFS(int startIndex)
{
Integer x;
QueueADT<Integer> traversalQueue = new LinkedQueue<Integer>();
UnorderedListADT<T> resultList = new UnorderedListArrayList<>();
if (!indexIsValid(startIndex))
return resultList.iterator();
boolean[] visited = new boolean[numVertices];
for (int i = 0; i < numVertices; i++)
visited[i] = false;
traversalQueue.enqueue(new Integer(startIndex));
visited[startIndex] = true;
while (!traversalQueue.isEmpty())
{
x = traversalQueue.dequeue();
resultList.addToRear(vertices[x.intValue()]);
//Find all vertices adjacent to x that have not been visited
// and queue them up
for (int i = 0; i < numVertices; i++)
{
if (adjMatrix[x.intValue()][i] && !visited[i])
{
traversalQueue.enqueue(new Integer(i));
visited[i] = true;
}
}
}
return new GraphIterator(resultList.iterator());
}
/**
* Returns an iterator that performs a breadth first search
* traversal starting at the given vertex.
*
* @param startVertex the vertex to begin the search from
* @return an iterator that performs a breadth first traversal
*/
public Iterator<T> iteratorBFS(T startVertex)
{
return iteratorBFS(getIndex(startVertex));
}
/**
* Returns an iterator that contains the indices of the vertices
* that are in the shortest path between the two given vertices.
*
* @param startIndex the starting index
* @param targetIndex the the target index
* @return the an iterator containing the indices of the
* of the vertices making the shortest path between
* the given indices
*/
protected Iterator<Integer> iteratorShortestPathIndices
(int startIndex, int targetIndex)
{
int index = startIndex;
int[] pathLength = new int[numVertices];
int[] predecessor = new int[numVertices];
QueueADT<Integer> traversalQueue = new LinkedQueue<Integer>();
UnorderedListADT<Integer> resultList =
new UnorderedListArrayList<>();
if (!indexIsValid(startIndex) || !indexIsValid(targetIndex) ||
(startIndex == targetIndex))
return resultList.iterator();
boolean[] visited = new boolean[numVertices];
for (int i = 0; i < numVertices; i++)
visited[i] = false;
traversalQueue.enqueue(new Integer(startIndex));
visited[startIndex] = true;
pathLength[startIndex] = 0;
predecessor[startIndex] = -1;
while (!traversalQueue.isEmpty() && (index != targetIndex))
{
index = (traversalQueue.dequeue()).intValue();
//Update the pathLength for each unvisited vertex adjacent
// to the vertex at the current index.
for (int i = 0; i < numVertices; i++)
{
if (adjMatrix[index][i] && !visited[i])
{
pathLength[i] = pathLength[index] + 1;
predecessor[i] = index;
traversalQueue.enqueue(new Integer(i));
visited[i] = true;
}
}
}
if (index != targetIndex) // no path must have been found
return resultList.iterator();
StackADT<Integer> stack = new LinkedStack<Integer>();
index = targetIndex;
stack.push(new Integer(index));
do
{
index = predecessor[index];
stack.push(new Integer(index));
} while (index != startIndex);
while (!stack.isEmpty())
resultList.addToRear(((Integer)stack.pop()));
return new GraphIndexIterator(resultList.iterator());
}
/**
* Returns an iterator that contains the shortest path between
* the two vertices.
*
* @param startIndex the starting index
* @param targetIndex the target index
* @return an iterator that contains the shortest path
* between the given vertices
*/
public Iterator<T> iteratorShortestPath(int startIndex,
int targetIndex)
{
UnorderedListADT<T> resultList = new UnorderedListArrayList<>();
if (!indexIsValid(startIndex) || !indexIsValid(targetIndex))
return resultList.iterator();
Iterator<Integer> it = iteratorShortestPathIndices(startIndex,
targetIndex);
while (it.hasNext())
resultList.addToRear(vertices[((Integer)it.next()).intValue()]);
return new GraphIterator(resultList.iterator());
}
/**
* Returns an iterator that contains the shortest path between
* the two vertices.
*
* @param startVertex the starting vertex
* @param targetVertex the target vertex
* @return an iterator that contains the shortest path between
* the given vertices
*/
public Iterator<T> iteratorShortestPath(T startVertex, T targetVertex)
{
return iteratorShortestPath(getIndex(startVertex),
getIndex(targetVertex));
}
/**
* Returns the weight of the least weight path in the network.
* Returns positive infinity if no path is found.
*
* @param startIndex the starting index
* @param targetIndex the target index
* @return the integer weight of the least weight path
* in the network
*/
public int shortestPathLength(int startIndex, int targetIndex)
{
int result = 0;
if (!indexIsValid(startIndex) || !indexIsValid(targetIndex))
return 0;
int index1, index2;
Iterator<Integer> it = iteratorShortestPathIndices(startIndex,
targetIndex);
if (it.hasNext())
index1 = ((Integer)it.next()).intValue();
else
return 0;
while (it.hasNext())
{
result++;
it.next();
}
return result;
}
/**
* Returns the weight of the least weight path in the network.
* Returns positive infinity if no path is found.
*
* @param startVertex the starting vertex
* @param targetVertex the target vertex
* @return the integer weight of teh least weight path
* in the network
*/
public int shortestPathLength(T startVertex, T targetVertex)
{
return shortestPathLength(getIndex(startVertex), getIndex(targetVertex));
}
/**
* Returns a minimum spanning tree of the graph.
*
* @return a minimum spanning tree of the graph
*/
public Graph getMST()
{
int x, y;
int[] edge = new int[2];
StackADT<int[]> vertexStack = new LinkedStack<int[]>();
Graph<T> resultGraph = new Graph<T>();
if (isEmpty() || !isConnected())
return resultGraph;
resultGraph.adjMatrix = new boolean[numVertices][numVertices];
for (int i = 0; i < numVertices; i++)
for (int j = 0; j < numVertices; j++)
resultGraph.adjMatrix[i][j] = false;
resultGraph.vertices = (T[])(new Object[numVertices]);
boolean[] visited = new boolean[numVertices];
for (int i = 0; i < numVertices; i++)
visited[i] = false;
edge[0] = 0;
resultGraph.vertices[0] = this.vertices[0];
resultGraph.numVertices++;
visited[0] = true;
// Add all edges that are adjacent to vertex 0 to the stack.
for (int i = 0; i < numVertices; i++)
{
if (!visited[i] && this.adjMatrix[0][i])
{
edge[1] = i;
vertexStack.push(edge.clone());
visited[i] = true;
}
}
while ((resultGraph.size() < this.size()) && !vertexStack.isEmpty())
{
// Pop an edge off the stack and add it to the resultGraph.
edge = vertexStack.pop();
x = edge[0];
y = edge[1];
resultGraph.vertices[y] = this.vertices[y];
resultGraph.numVertices++;
resultGraph.adjMatrix[x][y] = true;
resultGraph.adjMatrix[y][x] = true;
visited[y] = true;
// Add all unvisited edges that are adjacent to vertex y
// to the stack.
for (int i = 0; i < numVertices; i++)
{
if (!visited[i] && this.adjMatrix[i][y])
{
edge[0] = y;
edge[1] = i;
vertexStack.push(edge.clone());
visited[i] = true;
}
}
}
return resultGraph;
}
/**
* Creates new arrays to store the contents of the graph with
* twice the capacity.
*/
protected void expandCapacity()
{
T[] largerVertices = (T[])(new Object[vertices.length*2]);
boolean[][] largerAdjMatrix =
new boolean[vertices.length*2][vertices.length*2];
for (int i = 0; i < numVertices; i++)
{
for (int j = 0; j < numVertices; j++)
{
largerAdjMatrix[i][j] = adjMatrix[i][j];
}
largerVertices[i] = vertices[i];
}
vertices = largerVertices;
adjMatrix = largerAdjMatrix;
}
/**
* Returns the number of vertices in the graph.
*
* @return the integer number of vertices in the graph
*/
public int size()
{
return numVertices;
}
/**
* Returns true if the graph is empty and false otherwise.
*
* @return true if the graph is empty
*/
public boolean isEmpty()
{
return numVertices==0;
}
/**
* Returns true if the graph is connected and false otherwise.
*
* @return true if the graph is connected
*/
public boolean isConnected()
{
boolean result = true;
for(int i=0;i<numVertices;i++){
int temp=0;
temp=getSizeOfIterator(this.iteratorBFS(vertices[i]));
if(temp!=numVertices)
{
result = false;
break;
}
}
return result;
}
private int getSizeOfIterator(Iterator<T> iterator) {
int count=0;
while(iterator.hasNext()){
count++;
iterator.next();
}
return count;
}
/**
* Returns the index value of the first occurrence of the vertex.
* Returns -1 if the key is not found.
*
* @param vertex the vertex whose index value is being sought
* @return the index value of the given vertex
*/
public int getIndex(T vertex)
{
int result=-1;
for (int i=0;i<numVertices;i++){
if (vertex==vertices[i])
{ result=i;
break;
}
}
return result;
}
/**
* Returns true if the given index is valid.
*
* @param index the index whose validity is being queried
* @return true if the given index is valid
*/
protected boolean indexIsValid(int index)
{
return (index<vertices.length);
}
/**
* Returns a copy of the vertices array.
*
* @return a copy of the vertices array
*/
public Object[] getVertices()
{
Object[] temp = vertices;
return temp;
}
/**
* Inner class to represent an iterator over the elements of this graph
*/
protected class GraphIterator implements Iterator<T>
{
private int expectedModCount;
private Iterator<T> iter;
/**
* Sets up this iterator using the specified iterator.
*
* @param iter the list iterator created by a graph traversal
*/
public GraphIterator(Iterator<T> iter)
{
this.iter = iter;
expectedModCount = modCount;
}
/**
* Returns true if this iterator has at least one more element
* to deliver in the iteration.
*
* @return true if this iterator has at least one more element to deliver
* in the iteration
* @throws ConcurrentModificationException if the collection has changed
* while the iterator is in use
*/
public boolean hasNext() throws ConcurrentModificationException
{
if (!(modCount == expectedModCount))
throw new ConcurrentModificationException();
return (iter.hasNext());
}
/**
* Returns the next element in the iteration. If there are no
* more elements in this iteration, a NoSuchElementException is
* thrown.
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iterator is empty
*/
public T next() throws NoSuchElementException
{
if (hasNext())
return (iter.next());
else
throw new NoSuchElementException();
}
/**
* The remove operation is not supported.
*
* @throws UnsupportedOperationException if the remove operation is called
*/
public void remove()
{
throw new UnsupportedOperationException();
}
}
/**
* Inner class to represent an iterator over the indexes of this graph
*/
protected class GraphIndexIterator implements Iterator<Integer>
{
private int expectedModCount;
private Iterator<Integer> iter;
/**
* Sets up this iterator using the specified iterator.
*
* @param iter the list iterator created by a graph traversal
*/
public GraphIndexIterator(Iterator<Integer> iter)
{
this.iter = iter;
expectedModCount = modCount;
}
/**
* Returns true if this iterator has at least one more element
* to deliver in the iteration.
*
* @return true if this iterator has at least one more element to deliver
* in the iteration
* @throws ConcurrentModificationException if the collection has changed
* while the iterator is in use
*/
public boolean hasNext() throws ConcurrentModificationException
{
if (!(modCount == expectedModCount))
throw new ConcurrentModificationException();
return (iter.hasNext());
}
/**
* Returns the next element in the iteration. If there are no
* more elements in this iteration, a NoSuchElementException is
* thrown.
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iterator is empty
*/
public Integer next() throws NoSuchElementException
{
if (hasNext())
return (iter.next());
else
throw new NoSuchElementException();
}
/**
* The remove operation is not supported.
*
* @throws UnsupportedOperationException if the remove operation is called
*/
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
Java
1
https://gitee.com/CS-IMIS-23/20172309_javaProgramming.git
git@gitee.com:CS-IMIS-23/20172309_javaProgramming.git
CS-IMIS-23
20172309_javaProgramming
20172309_javaProgramming
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891