图作为一种重要的数据结构,在实际中是非常有用的。
package num;
import java.util.*;
import java.io.*;
class StackX
{
private final int SIZE =20;
private int[] st;
private int top;
public StackX()
{
st = new int[SIZE];
top = -1;
}
public void push(int j)
{
st[++top] = j;
}
public int pop()
{
return st[top–];
}
public int peek()
{
return st[top];
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Vertex
{
public char label;
public boolean wasVisited;
public Vertex(char lab)
{
this.label = lab;
wasVisited = false; //初始的时候,表示这个图的这个点未被访问过
}
}
class G //表示图
{
private final int MAX_VERTS = 20;
private Vertex[] vertexList;
private int adjMat[][]; //邻接矩阵
private int nVerts;
private StackX theStack; //栈类型
public G()
{
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int i = 0; i < MAX_VERTS; i++)
{
for(int j = 0; j < MAX_VERTS; j++)
adjMat[i][j] = 0;
}
theStack = new StackX();
}
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
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 == false)
{
return i;
}
return -1;
}
public void dfs() //注意,DFS采用栈来存储图中的节点
{
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 class Graph
{
public static void main(String args[])
{
G graph = new G();
graph.addVertex(‘A’);
graph.addVertex(‘B’);
graph.addVertex(‘C’);
graph.addVertex(‘D’);
graph.addVertex(‘E’);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(0, 3);
graph.addEdge(3, 4);
System.out.print(“Visits: “);
graph.dfs();
System.out.println();
}
}
以上是采用DFS,也就是深度优先遍历算法来执行的对图中所有节点进行的扫描。