版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlittlefive/article/details/80731703
图的深度优先遍历 和 广度优先遍历
参考资料:印度一大哥写的 数据结构和算法的java版本
其中图用的 一个顶点的数组 和一个关系的数组表示
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Stack; /** * 功能 : * date : 2018-06-19 09:57 * * @author : zcwang * @version : 0.0.4-snapshot * @since : JDK 1.8 */ public class Graph { private static final Logger LOGGER = LoggerFactory.getLogger(Graph.class); static class Vertex { public String lab; public boolean visited; public Vertex(final String lab) { this.lab = lab; this.visited = false; } } private final int maxVertices = 20; private final Vertex[] vertices; private final int[][] adjVertex; private int vertexCount; private final Stack<Integer> stack; public Graph() { this.vertices = new Vertex[this.maxVertices]; this.adjVertex = new int[this.maxVertices][this.maxVertices]; this.vertexCount = 0; this.stack = new Stack<>(); for (int i = 0; i < this.maxVertices; i++) { for (int j = 0; j < this.maxVertices; j++) { this.adjVertex[i][j] = 0; } } } public void addVertex(final String lab) { this.vertices[this.vertexCount++] = new Vertex(lab); } public void addEdge(final int start, final int end) { if (start >= 0 && start < this.vertexCount && end >= 0 && end < this.vertexCount) { this.adjVertex[start][end] = 1; this.adjVertex[end][start] = 1; } } public void displayVertex(final int v) { System.out.println(this.vertices[v].lab); } public int getAdjUnvisitedVertex(final int v) { for (int i = 0; i < this.vertexCount; i++) { if (this.adjVertex[v][i] == 1 && this.vertices[i].visited == false) { return i; } } return -1; } public void dfs() { this.stack.push(0); displayVertex(0); this.vertices[0].visited = true; while (!this.stack.isEmpty()) { final int v = getAdjUnvisitedVertex(this.stack.peek()); if (v == -1) { this.stack.pop(); } else { displayVertex(v); this.vertices[v].visited = true; this.stack.push(v); } } for (int i = 0; i < this.vertexCount; i++) { this.vertices[i].visited = false; } } public void bfs() { final LLQueue<Integer> queue = new LLQueue<>(); queue.enQueue(0); this.vertices[0].visited = true; displayVertex(0); while (!queue.isEmpty()) { final int v = queue.deQueue(); int result; while ((result = getAdjUnvisitedVertex(v)) != -1) { this.vertices[result].visited = true; displayVertex(result); queue.enQueue(result); } } for (int i = 0; i < this.vertexCount; i++) { this.vertices[i].visited = false; } } public static void main(final String[] args) { final Graph graph = new Graph(); graph.addVertex("A"); graph.addVertex("B"); graph.addVertex("C"); graph.addVertex("D"); graph.addVertex("E"); graph.addVertex("F"); graph.addVertex("G"); graph.addVertex("H"); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(2, 4); graph.addEdge(4, 5); graph.addEdge(4, 6); graph.addEdge(4, 7); graph.addEdge(1, 7); System.out.println("dfs:"); graph.dfs(); System.out.println("bfs:"); graph.bfs(); } }