无向图的深度优先搜索实例

说几句题外话,我的书架总摆着几本自己认为不错的java的基础书籍,一是<<Thinking in java>>,另外两本是第二版的<<Data Structures & Algorithms in Java>>和一本国人写的<<Java面向对象程序设计教程>>.
没有什么事做的时候,自己总是会拿起这几本翻一翻,免得有一些基础的东西忘记了。

下边的例子就是<<Data Structures & Algorithms in Java>>书的一个例子,并非我所写的,这一本书我觉得是最好

的一本java数据结构的入门书籍.现在把这一个例子记录在blog上,当作温习一下啦。

进入正题,深度优等搜索有三个规则:
1、如果可能,访问一个邻接的未访问的顶点,标记它,并把放入栈中。
2、当不能执行规则1时,如果栈不空,就从栈中弹出一个顶点。
3、如果不能执行规则1和规则2,就完成了整个搜索的过程。

Java代码 复制代码
  1. class StackX   
  2.    {   
  3.    private final int SIZE = 20;   
  4.    private int[] st;   
  5.    private int top;   
  6.   
  7.    public StackX()           // constructor   
  8.       {   
  9.       st = new int[SIZE];    // make array   
  10.       top = -1;   
  11.       }   
  12.   
  13.    public void push(int j)   // put item on stack   
  14.       { st[++top] = j; }   
  15.   
  16.    public int pop()          // take item off stack   
  17.       { return st[top--]; }   
  18.   
  19.    public int peek()         // peek at top of stack   
  20.       { return st[top]; }   
  21.   
  22.    public boolean isEmpty()  // true if nothing on stack   
  23.       { return (top == -1); }   
  24.   
  25.    }  // end class StackX   
  26.   
  27. class Vertex   
  28.    {   
  29.    public char label;        // label (e.g. 'A')   
  30.    public boolean wasVisited;   
  31.   
  32.    public Vertex(char lab)   // constructor   
  33.       {   
  34.       label = lab;   
  35.       wasVisited = false;   
  36.       }   
  37.    }  // end class Vertex   
  38.   
  39. class Graph   
  40.    {   
  41.    private final int MAX_VERTS = 20;   
  42.    private Vertex vertexList[]; // list of vertices   
  43.    private int adjMat[][];      // adjacency matrix   
  44.    private int nVerts;          // current number of vertices   
  45.    private StackX theStack;   
  46.   
  47.    public Graph()               // constructor   
  48.       {   
  49.       vertexList = new Vertex[MAX_VERTS];   
  50.                                           // adjacency matrix   
  51.       adjMat = new int[MAX_VERTS][MAX_VERTS];   
  52.       nVerts = 0;   
  53.       for(int y=0; y<MAX_VERTS; y++)      // set adjacency   
  54.          for(int x=0; x<MAX_VERTS; x++)   //    matrix to 0   
  55.             adjMat[x][y] = 0;   
  56.       theStack = new StackX();   
  57.       }  // end constructor   
  58.   
  59.    public void addVertex(char lab)   
  60.       {   
  61.       vertexList[nVerts++] = new Vertex(lab);   
  62.       }   
  63.   
  64.    public void addEdge(int start, int end)   
  65.       {   
  66.       adjMat[start][end] = 1;   
  67.       adjMat[end][start] = 1;   
  68.       }   
  69.   
  70.    public void displayVertex(int v)   
  71.       {   
  72.       System.out.print(vertexList[v].label);   
  73.       }   
  74. // 这一块是最核心的代码   
  75.    public void dfs()  // depth-first search   
  76.       {                                 // begin at vertex 0   
  77.       vertexList[0].wasVisited = true;  // mark it   
  78.       displayVertex(0);                 // display it   
  79.       theStack.push(0);                 // push it   
  80.   
  81.       while( !theStack.isEmpty() )      // until stack empty,   
  82.          {   
  83.          // get an unvisited vertex adjacent to stack top   
  84.          int v = getAdjUnvisitedVertex( theStack.peek() );   
  85.          if(v == -1)                    // if no such vertex,   
  86.             theStack.pop();   
  87.          else                           // if it exists,   
  88.             {   
  89.             vertexList[v].wasVisited = true;  // mark it   
  90.             displayVertex(v);                 // display it   
  91.             theStack.push(v);                 // push it   
  92.             }   
  93.          }  // end while   
  94.   
  95.       // stack is empty, so we're done   
  96.       for(int j=0; j<nVerts; j++)          // reset flags   
  97.          vertexList[j].wasVisited = false;   
  98.       }  // end dfs   
  99.   
  100.    // returns an unvisited vertex adj to v   
  101.    public int getAdjUnvisitedVertex(int v)   
  102.       {   
  103.       for(int j=0; j<nVerts; j++)   
  104.          if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)   
  105.             return j;   
  106.       return -1;   
  107.       }  // end getAdjUnvisitedVertex()   
  108.    }  // end class Graph   
  109.   
  110. class DFSApp   
  111.    {   
  112.    public static void main(String[] args)   
  113.       {   
  114.       Graph theGraph = new Graph();   
  115.       theGraph.addVertex('A');    // 0  (start for dfs)   
  116.       theGraph.addVertex('B');    // 1   
  117.       theGraph.addVertex('C');    // 2   
  118.       theGraph.addVertex('D');    // 3   
  119.       theGraph.addVertex('E');    // 4   
  120.   
  121.       theGraph.addEdge(01);     // AB   
  122.       theGraph.addEdge(12);     // BC   
  123.       theGraph.addEdge(03);     // AD   
  124.       theGraph.addEdge(34);     // DE   
  125.   
  126.       System.out.print("Visits: ");   
  127.       theGraph.dfs();             // depth-first search   
  128.       System.out.println();   
  129.       }  // end main()   
  130.    }  // end class DFSApp  
class StackX
   {
   private final int SIZE = 20;
   private int[] st;
   private int top;

   public StackX()           // constructor
      {
      st = new int[SIZE];    // make array
      top = -1;
      }

   public void push(int j)   // put item on stack
      { st[++top] = j; }

   public int pop()          // take item off stack
      { return st[top--]; }

   public int peek()         // peek at top of stack
      { return st[top]; }

   public boolean isEmpty()  // true if nothing on stack
      { return (top == -1); }

   }  // end class StackX

class Vertex
   {
   public char label;        // label (e.g. 'A')
   public boolean wasVisited;

   public Vertex(char lab)   // constructor
      {
      label = lab;
      wasVisited = false;
      }
   }  // end class Vertex

class Graph
   {
   private final int MAX_VERTS = 20;
   private Vertex vertexList[]; // list of vertices
   private int adjMat[][];      // adjacency matrix
   private int nVerts;          // current number of vertices
   private StackX theStack;

   public Graph()               // constructor
      {
      vertexList = new Vertex[MAX_VERTS];
                                          // adjacency matrix
      adjMat = new int[MAX_VERTS][MAX_VERTS];
      nVerts = 0;
      for(int y=0; y<MAX_VERTS; y++)      // set adjacency
         for(int x=0; x<MAX_VERTS; x++)   //    matrix to 0
            adjMat[x][y] = 0;
      theStack = new StackX();
      }  // end constructor

   public void addVertex(char lab)
      {
      vertexList[nVerts++] = new Vertex(lab);
      }

   public void addEdge(int start, int end)
      {
      adjMat[start][end] = 1;
      adjMat[end][start] = 1;
      }

   public void displayVertex(int v)
      {
      System.out.print(vertexList[v].label);
      }
// 这一块是最核心的代码
   public void dfs()  // depth-first search
      {                                 // begin at vertex 0
      vertexList[0].wasVisited = true;  // mark it
      displayVertex(0);                 // display it
      theStack.push(0);                 // push it

      while( !theStack.isEmpty() )      // until stack empty,
         {
         // get an unvisited vertex adjacent to stack top
         int v = getAdjUnvisitedVertex( theStack.peek() );
         if(v == -1)                    // if no such vertex,
            theStack.pop();
         else                           // if it exists,
            {
            vertexList[v].wasVisited = true;  // mark it
            displayVertex(v);                 // display it
            theStack.push(v);                 // push it
            }
         }  // end while

      // stack is empty, so we're done
      for(int j=0; j<nVerts; j++)          // reset flags
         vertexList[j].wasVisited = false;
      }  // end dfs

   // returns an unvisited vertex adj to v
   public int getAdjUnvisitedVertex(int v)
      {
      for(int j=0; j<nVerts; j++)
         if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
            return j;
      return -1;
      }  // end getAdjUnvisitedVertex()
   }  // end class Graph

class DFSApp
   {
   public static void main(String[] args)
      {
      Graph theGraph = new Graph();
      theGraph.addVertex('A');    // 0  (start for dfs)
      theGraph.addVertex('B');    // 1
      theGraph.addVertex('C');    // 2
      theGraph.addVertex('D');    // 3
      theGraph.addVertex('E');    // 4

      theGraph.addEdge(0, 1);     // AB
      theGraph.addEdge(1, 2);     // BC
      theGraph.addEdge(0, 3);     // AD
      theGraph.addEdge(3, 4);     // DE

      System.out.print("Visits: ");
      theGraph.dfs();             // depth-first search
      System.out.println();
      }  // end main()
   }  // end class DFSApp



输入结果:

Java代码 复制代码
  1. Visits:ABCDE  
Visits:ABCDE

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值