package com.rao.graph;
import java.util.LinkedList;
/**
* @author Srao
* @className BFS_DFS
* @date 2019/12/10 19:16
* @package com.rao.graph
* @Description 深度优先搜索 和 广度优先搜索
*/
public class BFS_DFS {
/**
* 图的顶点
*/
private static class Vertex{
int data;
Vertex(int data){
this.data = data;
}
}
/**
* 图(邻接表)
*/
private static class Graph{
private int size;
private Vertex[] vertices;
//存放每个顶点的链表
private LinkedList<Integer>[] adj;
Graph(int size){
this.size = size;
vertices = new Vertex[size];
adj = new LinkedList[size];
for (int i = 0; i < size; i++) {
vertices[i] = new Vertex(i);
adj[i] = new LinkedList();
}
}
}
/**
* DFS(深度优先搜索)
* @param graph:图
* @param start:起始访问点
* @param visited:是否被访问过,true表示被访问过
*/
public static void dfs(Graph graph, int start, boolean[] visited){
System.out.println(graph.vertices[start].data);
visited[start] = true;
for (int index : graph.adj[start]){
if (!visited[index]){
dfs(graph, index, visited);
}
}
}
/**
* BFS(广度优先搜索)
* @param graph:图
* @param start:起始访问点
* @param visited:是否被访问过,true表示被访问过
* @param queue:队列里面存放被遍历过的元素
*/
public static void bfs(Graph graph, int start, boolean[] visited, LinkedList<Integer> queue){
//队列的插入操作
queue.offer(start);
while (!queue.isEmpty()){
int front = queue.poll();
if (visited[front]){
continue;
}
System.out.println(graph.vertices[front].data);
visited[front] = true;
for (int index : graph.adj[front]){
queue.offer(index);
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.adj[0].add(1);
graph.adj[0].add(2);
graph.adj[0].add(3);
graph.adj[1].add(0);
graph.adj[1].add(3);
graph.adj[1].add(4);
graph.adj[2].add(0);
graph.adj[3].add(0);
graph.adj[3].add(1);
graph.adj[3].add(4);
graph.adj[3].add(5);
graph.adj[4].add(1);
graph.adj[4].add(3);
graph.adj[4].add(5);
graph.adj[5].add(3);
graph.adj[5].add(4);
System.out.println("图的深度优先遍历:");
dfs(graph, 0, new boolean[graph.size]);
System.out.println("图的广度优先遍历:");
bfs(graph, 0, new boolean[graph.size], new LinkedList<>());
}
}

输出结果如下:
图的深度优先遍历: 0 1 3 4 5 2 图的广度优先遍历: 0 1 2 3 4 5
来源:https://www.cnblogs.com/rao11/p/12018790.html