这里假设有这样的有向图
我们要对他进行深度优先搜索(基于邻接矩阵)
邻接矩阵的意思就是用矩阵的形式来表示图中顶点直接的邻接关系
如图所示我们可以得到矩阵如下
假设矩阵名字为matrix
matrix[3][4]的值表示的就是从顶点3到顶点4有向边的存在关系
深度搜索的含义就是说
/**
* 1. initial the matrix's value (1 means that two points are connected, 0 means disconnected)
初始化邻接矩阵的值,1表示a[i][j] 中 i 顶点和 j 顶点相连 反之不相连
* 2. set every point is not visited at start (false)
设置所有顶点的初始状态为false未访问状态
* 3. begin to dfsSerach with a start point (add the start point into visitList at first and make it's visit status true)
开始深度优先搜索设置搜索的起始值,讲起始值加入到访问链表中 并将起始值所代表的顶点访问状态改为true表示已经被访问过了
* 4. while current node is connected with the n'th node and the n'th node is not visited before.add the node into the visit List
当当前的顶点与第n个顶点相连数组值为1 并且 第n个顶点为未访问的状态的时候 将第n个顶点加入到访问链表中并且改变其访问状态
* 5. if we get the n'th node, supposed it as a start point and call step 3
第n个顶点找到之后,以第n个顶点为起点,重复步骤3,直到所有的点全都被访问
*
*/
import java.util.ArrayList;
import java.util.List;
/**
* 1. initial the matrix's value (1 means that two points are connected, 0 means disconnected)
* 2. set every point is not visited at start (false)
* 3. begin to dfsSerach with a start point (add the start point into visitList at first and make it's visit status true)
* 4. while current node is connected with the n'th node and the n'th node is not visited before.add the node into the visit List
* 5. if we get the n'th node, supposed it as a start point and call step 3
* @author zero
*
*/
public class adjMatrixDFS {
private List<Integer> visitList = new ArrayList<Integer>();
//initial the matrix's value (1 means that two points are connected, 0 means disconnected)
private int[][] matrix = {{1,0,1,0,1},{0,1,0,1,0},{1,1,1,0,1},{1,0,0,1,1},{1,0,0,0,0}};
//set every point is not visited at start
private Boolean[] visitStatus = {false,false,false,false,false};
public void dfsSerach(int visitNode) {
for(int i=0; i<5; i++) {
if((matrix[visitNode][i] == 1 )&&(visitStatus[i]==false)) {
visitList.add(i);
visitStatus[i] = true;
dfsSerach(i);
}else {
}
}
}
public void setInitNode(int startNode) {
visitList.add(startNode);
visitStatus[startNode] = true;
dfsSerach(startNode);
}
public void outSortResult() {
System.out.print("The sorted result is : ");
for(int i=0; i<visitList.size(); i++) {
System.out.print(visitList.get(i) + " ");
}
}
public static void main(String[] args) {
adjMatrixDFS amdfs = new adjMatrixDFS();
amdfs.setInitNode(1);
amdfs.outSortResult();
}
}
输入的结果为:
The sorted result is : 1 3 0 2 4