BFS与DFS

BFS 与DFS回顾

package graph;

import java.util.LinkedList;
import java.util.Queue;

public class Main {

    public void bfs(int[][] graph, int st) {
        boolean[] visit = new boolean[graph.length];
        Queue<Integer> que = new LinkedList<>();
        que.add(st);
        visit[st] = true;
        while (que != null) {
            int tmp = que.poll();
            System.out.println(tmp);
            for (int i = 0; i < graph[tmp].length; i++) {
                if (graph[tmp][i] == 1 && !visit[i]) {
                    que.offer(i);
                    visit[i] = true;
                }
            }
        }

    }

    public void dfs(int[][] graph,int st,boolean[]visit){
        visit[st] = true;
        for(int i=1;i<graph.length;i++){
            if(!visit[i]&&graph[st][i]==1){
                dfs(graph,i,visit);
            }
        }
        System.out.println(st);
    }
}

未完待续 温故知新 未央书斋

你可能感兴趣的:(刷题笔记,后端相关,dfs,java,bfs)