2011-11-11 42 views
2

我先写第一广度,深度和下面的图深度优先递归遍历:广度优先遍历形容词矩阵

enter image description here

据我了解,遍历应该是0 1 3 6 4 5 2 ...但我只得到深度第一次遍历,并为dfs(递归)和BFS,我越来越0 1 3 6 2 4 5.我不知道哪一个是正确的,我需要做什么来解决这个问题。

public void depthFirst(int vFirst,int n, int[] isvisited) 
    {  //vFirst = 0, n = 6 
    int v,i; 
    // st is a stack 
    st.push(vFirst); 

    while(!st.isEmpty()) 
    { 
     v = st.pop(); 
     if(isvisited[v]==0) 
     { 
      System.out.print(v); 
      isvisited[v]=1; 
     } 
     for (i = 0; i <= n; i++) 
     { 
      if((adjMatrix[v][i] == 1) && (isvisited[i] == 0)) 
      { 
       st.push(v); 
       isvisited[i]=1; 
       System.out.print(" " + i); 
       v = i; 
      } 
     } 
    } 

}

public void depthFirstRecursive(int w) { 
    int j;  //w = 0; 

    visited[w] = 1; 
    if (w == 0) { 
     System.out.print(w + " "); 
    } 

    for (j = 0; j <= 6; j++) { 
     if ((adjMatrix[w][j] == 1) && (visited[j] == 0)) { 
      System.out.print(j + " "); 

      depthFirstRecursive(j); 
     } 

    } 
} 

public void breadthFirst(int first, int p) { 
    int e;  // first = 0; p = 6 
    int[] nodeVisited = new int[7]; 
    que.add(first); 


    while (!que.isEmpty()) { 
     e = que.remove(); 
     if(nodeVisited[e]==0) 
      { 
       System.out.print(e); 
       nodeVisited[e]=1; 
      } 
     for (int i = 0; i <= p; i++) 
      { 

       if((adjMatrix[e][i] == 1) && (nodeVisited[i] == 0)) 
       { 
        que.add(e); 
        nodeVisited[i]=1; 
        System.out.print(" " + i); 
        e = i; 
       } 
      } 

    } 



} 


public static void main(String[] args) { 



         // 1 2 3 4 5 6 7 
    int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0}, 
          {1, 0, 0, 1, 1, 1, 0}, 
          {1, 0, 0, 0, 0, 0, 1}, 
          {0, 1, 0, 0, 0, 0, 1}, 
          {0, 1, 0, 0, 0, 0, 1}, 
          {0, 1, 0, 0, 0, 0 ,0}, 
          {0, 0, 1, 1, 1, 0, 0} }; 


     new myGraphs(adjMatrix); 
} 
+0

'st'和'que'是如何定义的? –

+2

是你的图表导向?如果不是这样,那么很难为无向图得到一个正确的结果。 –

+0

@ThomasJungblut st是一个堆栈,que是一个队列 = linkedlist TMan

回答

2

关于在BFS下面的代码片段:

que.add(e); 
nodeVisited[i]=1; 
System.out.print(" " + i); 
e = i; 

他们为什么你改变e并添加e要排队?这对我来说似乎不正确。

+0

这就是我能够通过邻接矩阵进行搜索的方式,如果我没有更改e,它只会搜索第0列。 – TMan

+0

@TMan号您可以在第一个循环中更改'e':e = que.remove(); '这和BFS如何工作。更深入地检查[BFS](http://en.wikipedia.org/wiki/Breadth-first_search)。 –

+0

不错,但所有的遍历方法都应该打印出来吗? – TMan

0
public void BFS(int start) 
{ 
    int v=a.length;//a[][] is adj matrix declared globally 
    boolean visited[]=new boolean[v];//indexing done from 1 to n 
    LinkedList<Integer> queue=new LinkedList<Integer>(); 
    visited[start]=true; 
    queue.add(start); 
    while(queue.size()!=0) 
    { 
     int x=queue.remove(); 
     System.out.print(x+" "); 
     for (int i=1; i < v; i++) 
      if((a[x][i] == 1) && (!visited[i])) 
      { 
       queue.add(i); 
       visited[i]=true; 
      } 
    } 
} 
+1

请评论你的回答。描述解决方案,使之与其他可能的解决方案相媲美。 –