前言
在深度优先查找的基础上,实现图之路径查找的Java版API
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package com;
public class DeepFirstPath {
private boolean[] marked; private int start; private int[] edgeTo;
public DeepFirstPath(Graph graph, int start) { this.marked = new boolean[graph.getNodeLength()]; this.start = start; this.edgeTo = new int[graph.getNodeLength()];
dfs(graph, start); }
private void dfs(Graph graph, int node) { marked[node] = true; for (Integer n : graph.adj(node)) { if (!marked[n]) { edgeTo[n] = node; dfs(graph, node); } }
}
public boolean hasPathTo(int node) { return marked[node]; }
public Stack<Integer> pathTo(int node) { if (!hasPathTo(node)) { return null; } Stack<Integer> path = new Stack<>(); for (int i = node; i != start; i = edgeTo[i]) { path.push(i); } path.push(start); return path; }
}
|
完成
哔哩哔哩——黑马程序员