[img]http://dl.iteye.com/upload/attachment/0072/8819/2c6e4927-0f08-3e44-86af-46ebdefe85dd.gif[/img]
遍历,直到图中所有顶点都被访问到为止。
下载源码:
遍历,直到图中所有顶点都被访问到为止。
import java.util.Stack;
// 图的邻接矩阵实现及深度优先搜索图dfs.java
//顶点类
class Vertex
{
public char label;
public boolean wasVisited;//此顶点是否被访问过
public Vertex(char lab) // constructor
{
label = lab;
wasVisited = false;
}
}
//图的邻接矩阵实现
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; // 存放顶点的数组
private int adjMat[][]; // 邻接矩阵
private int nVerts; // 当前的顶点数
private Stack<Integer> theStack;
public Graph()
{
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int y=0; y<MAX_VERTS; y++)
for(int x=0; x<MAX_VERTS; x++)
adjMat[x][y] = 0;
theStack = new Stack<Integer>();
}
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;
}
//显示顶点v
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
//深度优先遍历图
public void dfs() // depth-first search
{ // 从顶点 vertexList[0]开始搜索
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; // 访问v
displayVertex(v);
theStack.push(v); // 进栈
}
}
for(int j=0; j<nVerts; j++) //为了继续使用DFS,重置所有顶点的标志
vertexList[j].wasVisited = false;
}
//从邻接矩阵中判断顶点v是否有未访问过的邻接点
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j;
return -1;
}
}
public class DFSApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 (start for dfs)
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE
System.out.print("Visits: ");
theGraph.dfs();
System.out.println();
}
}
下载源码: