## 编程人 cdmana.com

### 数据结构-图-深度优先搜索算法(Java语言)

详细的代码可见github：

``https://github.com/AbitGo/myClassWork/tree/master/workspace_ds``

``````package com.company.ch6;

public class GraphFS {
private static boolean[] visited;

//深度优先搜索算法的实现
public static void DFSTraverse(IGraph g)throws Exception{
visited = new boolean[g.getVexNum()];
for (int v = 0; v < g.getVexNum(); v++) {
visited[v] = false;
}
for (int v = 0; v < g.getVexNum(); v++) {
//如果当前没被访问
if (visited[v] == false) {
DFS(g,v);
}
}
System.out.println();
}

public static void DFS(IGraph g,int v) throws Exception {
//该节点已经被访问过了
visited[v]=true;
System.out.print(g.getVex(v).toString()+" ");
if(!visited[w]){
DFS(g,w);
}
}
}
}
``````

``````package com.company.ch6;

public class MGraphTest {
public static void main(String[] args) throws Exception {
//无向图
Object[] param1_1_1= {"UDN",5,5,"ABCDE"};
MGraph mGraph1 = new MGraph();
mGraph1.createGraph(param1_1_1,param1_1_2);
GraphFS.BFSTraverse(mGraph1);
GraphFS.DFSTraverse(mGraph1);

//有向图
Object[] param1_2_1= {"UDN",5,5,"ABCDE"};
MGraph mGraph2 = new MGraph();
mGraph2.createGraph(param1_2_1,param1_2_2);
GraphFS.BFSTraverse(mGraph2);
GraphFS.DFSTraverse(mGraph2);
}
}
``````

``````"C:\Program Files\Java\jdk1.8.0_101\bin\java.exe"

A B D E C
A B C E D

A B D E C
A B C E D ``````
Scroll to Top