2016-05-21 159 views
0

我不知道爲什麼這個程序的輸出是不正確的。 它只是打印第一個訪問節點。據我所知,算法是正確的。 請幫我找到錯誤。 感謝BFS代碼(廣度優先搜索)

import java.util.Scanner; 
    public class bfs { 
    static void bf(int v,int []vis,int n,int [][]a){ 
    int []q; 
    int u; 
    int f=0,r=-1; 
    q=new int[20]; 
    q[++r]=v; 
    vis[v]=1; 
    while(f<=r){ 
     u=q[f]; 
     System.out.println(u); 
     for(int i=1;i<=n;i++){ 
      if(a[u][i]==1&&vis[i]==0){ 
       q[++f]=i; 
       vis[i]=1; 
      } 
     } 
     f++; 
     } 
    } 
public static void main(String[] args){ 
    int []vis=new int [20]; 
    int [][]a=new int [20][20]; 
    int source,n; 
    System.out.println("Enter the number of vertex"); 
    Scanner sc=new Scanner(System.in); 
    n=sc.nextInt(); 
    System.out.println("Enter the adjacency matrix"); 
    for(int i=1;i<=n;i++){ 
     for(int j=1;j<=n;j++) 
      a[i][j]=sc.nextInt(); 
     vis[i]=0; 
    } 
    System.out.println("Enter the source vertex\n"); 
    source=sc.nextInt(); 
    System.out.println("Nodes reached from "+source+"\n"); 
    bf(source,vis,n,a); 
    } 

} 
+1

什麼是正確的輸出?你應該發佈你的輸入測試用例和期望的輸出。如指南中所述,請創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – tmthydvnprt

回答

0

我相信你q[++f]=i;應該是q[++r]=i;,這是試圖以新節點追加到數組的末尾(因爲它被用作BFS隊列),而不是前面。