图的表示
class Vertex {
public char label;
public boolean wasVisited;
public boolean isInTree;
public Vertex(char label) {
this.label = label;
wasVisited = false;
isInTree = false;
}
}
dfs、bfs、mst
public class GraphDemo {
private final Vertex[] vertexList;
private final int[][] adjMat;
private int nVerts;
public GraphDemo() {
int MAX_VERTS = 20;
this.vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
}
public void addVertex(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].label);
}
public int getAdjUnvisitedVertex(int v) {
for (int i = 0; i < nVerts; i++) {
if (adjMat[v][i] == 1 && !vertexList[i].wasVisited) return i;
}
return -1;
}
public void dfs() {
Stack<Integer> theStack = new Stack<>();
vertexList[0].wasVisited = true;
displayVertex(0);
theStack.push(0);
while (!theStack.isEmpty()) {
int v = getAdjUnvisitedVertex(theStack.peek());
if (v == -1) theStack.pop();
else {
vertexList[v].wasVisited = true;
displayVertex(v);
theStack.push(v);
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].wasVisited = false;
}
}
public void bfs() {
Deque<Integer> theQueue = new LinkedList<>();
vertexList[0].wasVisited = true;
displayVertex(0);
theQueue.addFirst(0);
int v2;
while (!theQueue.isEmpty()) {
int v1 = theQueue.remove();
while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
vertexList[v2].wasVisited = true;
displayVertex(v2);
theQueue.addFirst(v2);
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].wasVisited = false;
}
}
public void mst() {
Stack<Integer> theStack = new Stack<>();
vertexList[0].wasVisited = true;
theStack.push(0);
while (!theStack.isEmpty()) {
int currentVertex = theStack.peek();
int v = getAdjUnvisitedVertex(currentVertex);
if (v == -1) theStack.pop();
else {
vertexList[v].wasVisited = true;
theStack.push(v);
displayVertex(currentVertex);
displayVertex(v);
System.out.print(" ");
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].wasVisited = false;
}
}
public static void main(String[] args) {
GraphDemo gd = new GraphDemo();
gd.addVertex('0');
gd.addVertex('1');
gd.addVertex('2');
gd.addVertex('3');
gd.addVertex('4');
gd.addVertex('5');
gd.addVertex('6');
gd.addVertex('7');
gd.addEdge(0, 3);
gd.addEdge(0, 4);
gd.addEdge(1, 4);
gd.addEdge(2, 5);
gd.addEdge(3, 6);
gd.addEdge(4, 6);
gd.addEdge(5, 7);
gd.addEdge(6, 7);
System.out.println("visit: dfs ");
gd.dfs();
System.out.println("\n+++++ bfs +++++++");
gd.bfs();
System.out.println("\n最小生成树");
gd.mst();
}
}