2016-04-15 21 views
-2

C++コードを使用してBFSツリーを作成しようとしています。私はかなり私のコードが動作していることを確信していますが、私は訪問されたノードをマークするためにtrueの(最後のif文で)ブール値を 'explored'に変更しようとするたびに、次の関数のループ。私は以下のようにBFS関数を投稿しました。なぜ誰かが値が偽に変わるのを私に正確に説明できれば、どういうことが間違っているかわからないので、非常に役立ちます。適切な形式でboolの値が変更されましたが、while文の次のループで変更されます。

void BFS(int s,int n, vector<vector<int> > node_list) { 
    queue<int> Q; 


    bool *explored = new bool[n+1];// it Keeps track of explored vertices 

    for (int i = 1; i <= n; ++i)// Initialization of all vertices as unexplored 
    explored[i] = false; 
    Q.push(s);// Pushing of initial vertex to the queue 
    explored[s] = true; // marking it as explored 
    cout << "Breadth first Search starting from vertex "; 
    cout << s << " : " << endl; 

    while (!Q.empty()) { 
     int v = Q.front(); 
     Q.pop(); 
     cout << v << " "; 
     cout << explored[1]<<explored[2]<<explored[3]<<explored[4]<<endl; 
     vector<int> current_list = node_list[v-1]; 

     for (int i = 0;i<current_list.size();i++){ 
      for (int w = 1; w <= n; ++w){ 
       if ((w == current_list[i]) && (explored[w] != true)) { 
        cout << "in if: "<< w<<", "<<explored[w]<< endl; 
        Q.push(w); 
        explored[w] = true; 
       } 
      } 
     } 
    cout << endl; 
    delete [] explored; 
    } 
} 
+2

3つのネストループがあります。これらのどれが "次のループ"であるかを指摘できますか?また、理想的には、問題を実際に示す出力を伴う最小限の完全な例を示します。私は問題を再現するためにその1つの関数をコンパイルできません。 – Useless

+0

トピックはほとんどありませんが、 'node_list'だけを読んでいますが、それは価値のあるものです(ベクトルのベクトルを... ...)。 –

+1

もう1つの問題は、一般に、1ベースの配列処理を0ベースの処理とミックスすることは、いくつかのポイントで何らかのオフ・バイ・エラーが発生するレシピです。 C++では、配列/バッファは0ではなく1から始まります。誰かが1ベースの処理を偽造しようとするたびに1ドルを得た後、別のバグがあると、私は豊かな人になります。 – PaulMcKenzie

答えて

3

void BFS(int s,int n, vector<vector<int> > node_list) { 
    queue<int> Q; 

    bool *explored = new bool[n+1]; // it Keeps track of explored vertices 

    for (int i = 1; i <= n; ++i) // Initialization of all vertices as unexplored 
     explored[i] = false; 

    Q.push(s); // Pushing of initial vertex to the queue 
    explored[s] = true; // marking it as explored 
    cout << "Breadth first Search starting from vertex "; 
    cout << s << " : " << endl; 

    while (!Q.empty()) { 
     int v = Q.front(); 
     Q.pop(); 
     cout << v << " "; 
     cout << explored[1]<<explored[2]<<explored[3]<<explored[4]<<endl; 
     vector<int> current_list = node_list[v-1]; 

     for (int i = 0;i<current_list.size();i++){ 
      for (int w = 1; w <= n; ++w){ 
       if ((w == current_list[i]) && (explored[w] != true)) { 
        cout << "in if: "<< w<<", "<<explored[w]<< endl; 
        Q.push(w); 
        explored[w] = true; 
       } 
      } 
     } 
     cout << endl; 
     delete [] explored; 
    } 
} 

それはあなたが動的に割り当てられたexplored各反復を削除することを確認するのは簡単です。

関連する問題