Bootstrap

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

图的遍历方式有俩种:

  • 深度优先遍历(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 
;