您的位置:首页 > 其它

图算法-深度优先搜索和广度优先搜索

2018-03-13 17:36 232 查看
package Graph;

import sun.misc.Queue;

import java.util.Stack;

public class DepthFirstPaths {
private boolean[] marked ;//已经经过的点
private int[] edgeTo; //到达当前定点的上一个定点
private final int s;

public DepthFirstPaths(Graph g,int s){
marked=new boolean[g.V()];
edgeTo=new int[g.V()];
this.s=s;
dfs(g,s);
}
/**
* .
* 使用深度优先搜索获得起点s到指定定点v的路径
*/
public void dfs(Graph g,int v){
marked[v]=true;
for(int w:g.adj(v)){
if(!marked[w]){
edgeTo[w]=v;
dfs(g,w);
}
}
}

/**
* .
* 使用广度优先搜索获得起点s到指定定点v的最短路径
*/
public void dfs1(Graph g,int v) throws InterruptedException {
Queue<Integer> que=new Queue<Integer>();
marked[v]=true;
que.enqueue(v);
while(!que.isEmpty()){
int w=que.dequeue();
for(int i:g.adj(w)){
if(!marked[i]){
marked[i]=true;
que.enqueue(i);
edgeTo[i]=w;
}
}
}
}
//获得起点s到指定定点v的路径
public Iterable<Integer> pathTo(int v){
if(marked[v]) {
Stack<Integer> path = new Stack<Integer>();
for(int i=v;i!=s;i=edgeTo[i]){
path.push(i);
}
path.push(s);
return path;
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: