[数据结构] - 图的基本实现
package p1;
import java.util.LinkedList;
import java.util.Queue;
/**
* 图 -- (邻接表的实现)
* @author Guozhu Zhu
* @date 2019/3/26
* @version 1.0
*
*/
public class Demo01 {
public static class Vertex{
int data;
public Vertex(int data) {
this.data = data;
}
}
public static class Graph{
int size = 0;
public Vertex[] vertexes;
public LinkedList<Integer>[] adj;
public Graph(int size) {
this.size = size;
vertexes = new Vertex[size];
adj = new LinkedList[size];
for (int i = 0; i < size; i++) {
vertexes[i] = new Vertex(i);
adj[i] = new LinkedList();
}
}
}
//DFS
public void DFS(Graph graph, int start, boolean[] visited) {
System.out.println(graph.vertexes[start].data);
visited[start] = true;
for (int index : graph.adj[start]) {
if (!visited[index]) {
DFS(graph, index, visited);
}
}
}
//BFS
public void BFS(Graph graph, int start, boolean[] visited) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(start);
while (!queue.isEmpty()) {
int front = queue.poll();
if (!visited[front]) {
System.out.println(graph.vertexes[front].data);
visited[front] = true;
for (int index : graph.adj[front]) {
queue.offer(index);
}
}
}
}
/* ========== Test ==========
* [0] -> 1 -> 2
* [1] -> 0
* [2] -> 1
* DFS: 0, 1, 2
* BFS: 0, 1, 2
* */
public static void main(String[] args) {
Demo01 demo = new Demo01();
Graph graph = new Graph(3);
graph.adj[0].add(1);
graph.adj[0].add(2);
graph.adj[1].add(0);
graph.adj[2].add(1);
System.out.println("图的深度遍历算法");
demo.DFS(graph, 0, new boolean[3]);
System.out.println("图的广度遍历算法");
demo.BFS(graph, 0, new boolean[3]);
}
}