簡體   English   中英

圖 BFS 遍歷 - C++

[英]Graph BFS Traversal - C++

給定一個無向且不連通的圖 G(V, E),打印其 BFS 遍歷。 在這里你需要考慮你只需要打印從頂點 0 開始的 BFS 路徑。 V 是圖 G 中存在的頂點數,頂點從 0 到 V-1 編號。 E 是圖 G 中存在的邊數。注意:1. 在鄰接矩陣中獲取圖輸入。 2. Handle for Disconnected Graphs as well 輸入格式: 第 1 行:兩個整數 V 和 E(以空格分隔) 接下來的“E”行,每行有兩個以空格分隔的整數,“a”和“b”,表示存在頂點 'a' 和頂點 'b' 之間的邊。 Output Format: BFS Traversal (以空格分隔) Constraints: 2 <= V <= 1000 1 <= E <= 1000 Sample Input 1: 4 4 0 1 0 3 1 2 2 3 Sample Output 1: 0 1 3 2 請告訴代碼有什么問題。

這是代碼:

#include <iostream>
using namespace std;
#include <queue>

void print(int** edges, int V, int sv, bool* visited){
    queue<int> pq;
    pq.push(sv);
    visited[sv] = true;

    while(!pq.empty()){
        int ans = pq.front();
        cout << ans << " ";
        pq.pop();

        for(int i = 0; i < V; i++){
            if(ans == i){
                continue;
            }
            if(edges[ans][i] == 1 && !visited[i]){
                pq.push(i);
                visited[i] = true;
            }
        }

    }

}   
void BFS(int** edges, int V){
    bool* visited = new bool[V];
    for(int i = 0; i < V; i++){
        visited[i] = false;
    }
    for(int i = 0; i < V; i++){
        if(!visited[i]){
            print(edges, V, i, visited);
        }
    }
    delete [] visited;
}






int main() {
    int V, E;
    cin >> V >> E;

    int**edges = new int*[V];
    for(int i = 0; i < V; i++){
        edges[i] = new int[V];
        for(int j = 0; j < V; j++){
            edges[i][j] = 0;
        }
    }
    for(int i = 0; i < E; i++){
        int f, s;
        cin >> f >> s;
        edges[f][s] == 1;
        edges[s][f] == 1;
    }



    BFS(edges, V);

    for(int i = 0; i < V; i++){
        delete [] edges[i];
    }
    delete [] edges;

  /*

       Write Your Code Here
       Complete the Rest of the Program
       You have to take input and print the output yourself

  */


}

我認為唯一的問題是我在從命令行讀取參數的部分看到的一個小錯誤。 該算法本身看起來不錯。 讀取邊緣時需要使用賦值運算符=而不是比較運算符==

edges[f][s] = 1;
edges[s][f] = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM