图
package graph;
import java.util.*;
public class Graph {
private Vertex[] vertexList;
private int[][] adjMat;
private int nVerts;
private Stack<Integer> theStack;
private Queue<Integer> theQueue;
private final int MAX_VERTS = 20;
public Graph() {
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
for (int i = 0; i < MAX_VERTS; i++) {
for (int j = 0; j < MAX_VERTS; j++) {
adjMat[i][j] = 0;
}
}
nVerts = 0;
theStack = new Stack();
theQueue = new LinkedList<Integer>();
}
public void insert(char label) {
vertexList[nVerts++] = new Vertex(label);
}
public void addEdge(int start, int end) {
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
public void displayVertex(int v) {
System.out.print(vertexList[v].lable);
}
public void depthFirstSearch() {
vertexList[0].isVisited = true;
displayVertex(0);
theStack.push(0);
while (!theStack.isEmpty()) {
int currentVert = theStack.peek();
int v = getAdjUnVisited(currentVert);
if (v == -1) {
theStack.pop();
} else {
vertexList[v].isVisited = true;
displayVertex(v);
theStack.push(v);
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].isVisited = false;
}
}
public int getAdjUnVisited(int v) {
for (int i = 0; i < nVerts; i++) {
if (adjMat[v][i] == 1 && !vertexList[i].isVisited) {
return i;
}
}
return -1;
}
public void breadthFirstSearch() {
vertexList[0].isVisited = true;
displayVertex(0);
theQueue.add(0);
int v1;
int v2;
while (!theQueue.isEmpty()) {
v1 = theQueue.remove();
while ((v2 = getAdjUnVisited(v1)) != -1) {
vertexList[v2].isVisited = true;
displayVertex(v2);
theQueue.add(v2);
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].isVisited = false;
}
}
}
顶点
package graph;
public class Vertex {
public char lable;
public boolean isVisited;
public Vertex(char lable) {
this.lable = lable;
isVisited = false;
}
}
测试类
package graph;
public class GraphTest {
public static void main(String[] args) {
Graph graph = new Graph();
graph.insert('A');
graph.insert('B');
graph.insert('C');
graph.insert('D');
graph.insert('E');
graph.addEdge(0,1);
graph.addEdge(1,2);
graph.addEdge(0,3);
graph.addEdge(0,4);
graph.depthFirstSearch();
System.out.println();
graph.breadthFirstSearch();
}
}