深度优先搜索(DFS)和广度优先搜索(BFS) 无向图


在程序中,在搜索一幅图时遇到有多边需要遍历的情况的时候,我们会选择其中一条并将其他通道留到以后继续搜索。

  • 在深度优先搜索中,我们用了一个可以下压的栈,来支持递归搜索方法。使用LIFO(后进先出)的规则来描述压栈和走迷宫时先探索相邻的通道类似。从有待搜索的通道中选择最晚遇到的那条。
  • 在广度优先搜索中,我们希望按照起点的距离的顺序遍历所有顶点,使用FIFO(先进先出)队列代替栈即可。我们将从有待搜索的通道中选择最早遇到的那条。

DFS寻找路径

public class DeapthFisrtPaths
{	private boolean[] marked;	
	private int[] edgeTo;
    private final int s;
 
 
 public DeapthFirstPaths(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(!hashPathTo(v)) return null;
     Stack<Integet> path = new Stack<Integer>();
     for(int x=v; x!=s; x= edgeTo[x])
     {
         path.push(x);
     }
     path.push(s);
     return path;
 }


BFS寻找路径

public class BreathFisrtPaths
{	private boolean[] marked;	
	private int[] edgeTo;
    private final int s;
 
 
 
 public BreathFirstPaths(Graph G, int s)
 {
     marked = new  boolean[G.V()];
     edgeTo = new int{G.V()]
     this.s = s;
     bfs(G,s);
 }
 
 private void bfs(Graph G, int v)
 {
     Queue<Integer> queue = new Queue<Integer>();
     marked[v] = true;
     queue.enqueue(s);
     
     while(!queue.isEmpty())
     {
        for(int w:G.adj(v))
        {
             if(!marked[w])
             {
                 edgeTo[w] = v;
                 queue.dequeue(w);} 
            }
     }
 }
 
 public boolean hasPathTo(int v)
 {
     return marked[v];
 }
 
 public Iterable<Integer> pathTo(int V)
 {
     if(!hashPathTo(v)) return null;
     Stack<Integet> path = new Stack<Integer>();
     for(int x=v; x!=s; x= edgeTo[x])
     {
         path.push(x);
     }
     path.push(s);
     return path;
 }
}
发布了12 篇原创文章 · 获赞 0 · 访问量 895

猜你喜欢

转载自blog.csdn.net/EPFL_Panda/article/details/100774833