DFS(深度优先搜索)

1.DFS的定义:

深度优先搜索(Depth-First Search),从初始访问结点出发,我们知道初始访问结点可能有多个邻接结点,深度优先遍历的策略就是首先访问第一个邻接结点,然后再以这个被访问的邻接结点作为初始结点,访问它的第一个邻接结点。总结起来可以这样说:每次都在访问完当前结点后首先访问当前结点的第一个邻接结点。

这样的访问策略是优先往纵向挖掘深入,而不是对一个结点的所有邻接结点进行横向访问。过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次.

2.图解(摘自百度百科)

上图是一个无向图,如果我们从A点发起深度优先搜索(以下的访问次序并不是唯一的,第二个点既可以是B也可以是C,D),则我们可能得到如下的一个访问过程:A->B->E(没有路了!回溯到A)->C->F->H->G->D(没有路,最终回溯到A,A也没有未访问的相邻节点,本次搜索结束)

1)每次深度优先搜索的结果必定是图的一个连通分量;

2)一个图的DFS序列不一定唯一,它与算法、图的存储结构以及初始出发点有关

3.递归DFS的步骤

 1)访问初始结点v,并标记结点v为已访问。

 2)查找结点v的第一个邻接结点w。

 3)若w存在,则继续执行4,否则算法结束。

 4)若w未被访问,对w进行深度优先遍历递归(即把w当做另一个v,然后进行步骤123)。

 5)查找结点v的w邻接结点的下一个邻接结点,转到步骤3。
4.代码部分

package Graph;
class Node {
    int x;//数值域
    Node next;//结点域
    public Node(int x) {
        this.x = x;
        this.next = null;
    }
}
public class DFS {

	    public Node first;//开始结点
	    public Node last;//结束结点

	    public static int run[] = new int[9];//标记是否已访问过
	    public static DFS head[] = new DFS[9];

	    public static void dfs(int current) {
	        run[current] = 1;
	        System.out.print("[" + current + "]");

	        while (head[current].first != null) {
	            if(run[head[current].first.x] == 0) { //如果顶点尚未遍历,就进行dfs递归
	                dfs(head[current].first.x);
	            }
	            head[current].first = head[current].first.next;
	        }
	    }

	    public boolean isEmpty() {
	        return first == null;
	    }
	    public void print() {
	        Node current = first;
	        while(current != null) {
	            System.out.print("[" + current.x + "]");
	            current = current.next;
	        }
	        System.out.println();
	    }
	    public void insert(int x) {
	        Node newNode = new Node(x);
	        if(this.isEmpty()) {
	            first = newNode;
	            last = newNode;
	        }
	        else {
	            last.next = newNode;
	            last = newNode;
	        }
	    }

	    public static void main(String[] args) {
	        int Data[][] = { {1,2}, {2,1}, {1,3}, {3,1}, {2,4}, {4,2},
	                {2,5}, {5,2}, {3,6}, {6,3}, {3,7}, {7,3}, {4,5}, {5,4},
	                {6,7}, {7,6}, {5,8}, {8,5}, {6,8}, {8,6} };
	        int DataNum;
	        int i,j;
	        System.out.println("图形的邻接表内容为:");
	        for(i=1;i<9;i++) {
	            run[i] = 0;
	            head[i] = new DFS();
	            System.out.print("顶点" + i + "=>");
	            for (j=0;j<20;j++) {
	                if(Data[j][0] == i) {
	                    DataNum = Data[j][1];
	                    head[i].insert(DataNum);
	                }
	            }
	            head[i].print();
	        }
	        System.out.println("深度优先遍历顶点:");
	        dfs(1);//调用dfs递归函数,开始结点为1
	        System.out.println("");
	    }

}

5.结果




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值