[JAVA] DFS与BFS代码实现

https://www.bilibili.com/video/av25761720
https://www.bilibili.com/video/av25763384
(BFS与DFS介绍视频,十分感谢“正月点灯笼”这位up主,我是看了该up主的视频然后自己编写java版程序)
[JAVA] DFS与BFS代码实现_第1张图片
这个是路线图,下面代码所写的二位数组是基于这个图编写的
至于图中右上角的文字和路线之间的数字请忽略

DFS

import java.util.Stack;

public class DFS {
    public static void main(String[] args) {
        int[][] graph = new int[6][6];
        graph[0][1] = 1;
        graph[0][3] = 1;
        graph[1][2] = 1;
        graph[1][4] = 1;
        graph[2][5] = 1;
        graph[3][4] = 1;
        graph[4][0] = 1;
        graph[4][5] = 1;
        graph[5][0] = 1;
        graph[5][1] = 1;

        printDFS(graph, 0,5);
    }

    public static void  printDFS(int[][] graph,int s,int e) {
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(s);
        boolean visited[] = new boolean[6];//默认为false
        visited[s] = true;

        while(!stack.isEmpty()){
            int vertex = stack.pop();

            int[] nodes = graph[vertex];
            for(int i =0; i<nodes.length;i++){
                if(!visited[i] && nodes[i]>0){ //还未访问
                    stack.push(i);
                    visited[i] = true;
                }
            }

            System.out.print(vertex+" ");
        }
    }
}

BFS

public class BFS {
    public static void main(String[] args) {
        int[][] graph = new int[6][6];
        graph[0][1] = 1;
        graph[0][3] = 1;
        graph[1][2] = 1;
        graph[1][4] = 1;
        graph[2][5] = 1;
        graph[3][4] = 1;
        graph[4][0] = 1;
        graph[4][5] = 1;
        graph[5][0] = 1;
        graph[5][1] = 1;
        printBFS(graph,0);
        
    public static void printBFS(int[][] graph,int s){
        boolean[] visited  = new boolean[graph.length];
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;

        int[] bfs = new int[graph.length];
        int j = 0;
        while (!queue.isEmpty()){

            int vertex = queue.poll();
            int[] nodes = graph[vertex];

            for(int i = 0; i < nodes.length; i++){
                if(!visited[i] && nodes[i]!=0){
                    queue.add(i);
                    visited[i] = true;
                }
            }

            bfs[j] = vertex;
            j++;
            System.out.print(vertex+" ");
        }


    }
}

你可能感兴趣的:([JAVA] DFS与BFS代码实现)