我試圖在鄰接矩陣的廣度優先搜索期間跟蹤并打印每個節點的深度。public class steptwo {static String matrixFileName = "matrix.txt";static int[][] matrix;static int dimensions = 0;public static void main(String[] args) { matrix = analyzeFile(); bft();}static void bft(){ Scanner input = new Scanner(System.in); System.out.println("Please enter the source vertex, 0 to " + (matrix.length-1) + "."); int source = input.nextInt()+1; //Testing for valid vertex while (source > matrix.length) { System.out.println("Invalid vertex, please enter another from 0 to " + (matrix.length-1) + "."); source = input.nextInt()+1; } input.close(); boolean[] visited = new boolean[matrix.length]; visited[source - 1] = true; Queue<Integer> queue = new LinkedList<>(); queue.add(source); int height = 0; System.out.println("The breadth first order is: "); while(!queue.isEmpty()){ System.out.print(queue.peek()-1 + " ---> H"); int x = queue.poll(); int i; for(i = 0 ; i < matrix.length; i++){ if(matrix[x-1][i] == 1 && visited[i] == false){ queue.add(i+1); visited[i] = true; height++; } } System.out.print(height + "\n"); }}我正在尋找這樣格式的輸出Please enter the source vertex, 0 to 7.0The breadth first order is: 0 ---> H51 ---> H62 ---> H63 ---> H64 ---> H75 ---> H76 ---> H77 ---> H7我確信我只是錯過了一些愚蠢的東西,但我不知所措。我需要跟蹤訪問的每個頂點的深度。鄰接矩陣已成功從 .txt 文件中讀取,并且在我的其他方法中運行良好。我可以是任意大小的簡單,也可以不是。任何意見表示贊賞,謝謝。如果需要更多信息,請告訴我。
1 回答

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
用 N 個整數創建數組“深度”,其中 N 是節點數并將其傳遞到 BFS
在 BFS 中,假設您將頂點“u”出列,您會發現它的鄰居,并且對于“u”的每個新發現的鄰居“v”,你設置depth[v]=depth[u] + 1:
if(matrix[x-1][i] == 1 && visited[i] == false){
queue.add(i+1);
visited[i] = true;
depth[i] = depth[x]+1;
}
添加回答
舉報
0/150
提交
取消