简体   繁体   中英

DFS Algorithm implementation using C++ STL

I have recently learnt DFS algorithm and tried to implement using C++ and STL concept.But while running the code with gcc it is giving me some error.Could someone please advice where the mistake has been done at my end?

The error is

exited with code=3221225477 in 2.75 seconds

Please find below the full code below:

#include <bits/stdc++.h>
using namespace std;

void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v); //singly linked ,not bidirectional
}

void DFS(vector<int> adj[], int v, vector<bool> &vis)
{
    vis[v] = true;
    cout << v << " ";
    //for(int i=0;i<adj[v].size() ; i++)
    for (auto i : adj[v])
    {
        //if(!vis[adj[v][i]])
        if (vis[i] == false)
            DFS(adj, i, vis);
    }
}

int main()
{
    vector<int> adj[5];
    vector<bool> visited(5, false);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 2, 4);
    addEdge(adj, 3, 5);
    addEdge(adj, 4, 5);
    DFS(adj, 1, visited);
}

I found the following bugs in your code

  1. #include <bits/stdc++.h> . Do not use this header. Use the needed C++ headers
  2. using namespace std; Do not use this. Use qualified names
  3. vector<int> adj[5]; fo never and under no circumstances use plain C-Style arrays. In your case you need a vector of vector
  4. Both of your vector/array dimensions are one to small.

You add edge numbers up to 5. But your array/vector has only 5 elements. In C++ array indices start counting with 0. So, a vector v with 5 elements has element v[0], v[1], v[2], v[3], v[4]. If you try to access the index 5, you will have an out of bounds error. The program will crash.

The std::vector 's at() function will also be your friend.

Simply increase array sizes.

  vector<int> adj[6];                  // 6 elements needed
  vector<bool> visited(6, false);      // 6 elements needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM