图算法-深度优先搜索和广度优先搜索
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;
}
}
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;
}
}
相关文章推荐
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 图的基本算法——广度优先搜索和深度优先搜索
- 算法导论-图的搜索算法之深度优先搜索和广度优先搜索
- 【算法——02】图的遍历——BFS广度优先搜索、DFS深度优先搜索
- 【游戏编程】AI-迷宫寻路算法-深度优先搜索和广度优先搜索
- AI-迷宫寻路算法-深度优先搜索和广度优先搜索
- 【算法学习】二、深度优先搜索与广度优先搜索
- 面试题常见算法之图的广度优先搜索和深度优先搜索
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 算法之深度优先搜索和广度优先搜索
- 深度优先搜索算法
- 【游戏编程】AI-迷宫寻路算法-深度优先搜索和广度优先搜索
- 深度优先搜索和广度优先搜索
- 广度优先搜索与深度优先搜索
- 深度优先搜索与广度优先搜索
- 【转载】【算法】DFS深度优先搜索
- (算法入门)基本图论-深度优先搜索之JAVA实现
- 深度优先搜索1-城堡问题(算法基础 第6周)
- 深度优先搜索1-A Knight's Journey(算法基础 第6周)
- 深度优先搜索2-Sudoku(算法基础 第7周)