深度优先遍历DFS 与 广度优先遍历BFS(java实现)

本文介绍了图的两种遍历方法——深度优先遍历(DFS)和广度优先遍历(BFS)。DFS利用栈和递归,从一个起点开始,将相邻未访问的点依次入栈直至栈空。BFS则基于队列,从起点出发,将相邻未访问的点加入队列,直到队列为空,实现遍历。
摘要由CSDN通过智能技术生成

图的遍历方式有俩种:

  • 深度优先遍历(DFS)
  • 广度优先遍历(BFS)

(1)深度优先遍历(利用栈和递归来实现)
思路:先以一个点为起点,这里假如是点A,那么就将A相邻的点放入堆栈,然后在栈中再取出栈顶的顶点元素(假如是点B),再将B相邻的且没有访问过的点放入栈中,不断这样重复操作直至栈中元素清空。这个时候你每次从栈中取出的元素就是你依次访问的点,以此实现遍历。

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值