用jiava语言写出深度遍历算法
时间: 2023-03-09 19:23:19 浏览: 104
面试-Java一些常见面试题+题解之算法-Algorithm.zip
我可以用Java语言来写出深度优先搜索算法:public class DFS {
private boolean[] marked;
private int[] edgeTo;
// 遍历起点
private final int s;
public DFS(Graph G, int s) {
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
this.s = s;
dfs(G, s);
}
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
}
}
public boolean hasPathTo(int v) {
return marked[v];
}
public Iterable<Integer> pathTo(int v) {
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x])
path.push(x);
path.push(s);
return path;
}
}
阅读全文