简体   繁体   English

使用C ++ STL的DFS算法实现

[英]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? 我最近学习了DFS算法并尝试使用C ++和STL概念实现,但是在用gcc运行代码时却给了我一些错误,有人可以建议我最后的错误在哪里吗?

The error is 错误是

exited with code=3221225477 in 2.75 seconds 在2.75秒内以code = 3221225477退出

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> . #include <bits/stdc++.h> Do not use this header. 不要使用此标头。 Use the needed C++ headers 使用所需的C ++标头
  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. 永远不要在任何情况下都不要使用纯C样式数组。 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. 您最多可以添加5个边号。但是您的数组/向量只有5个元素。 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]. 在C ++中,数组索引从0开始计数。因此,具有5个元素的向量v具有元素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. 如果您尝试访问索引5,将出现超出范围的错误。 The program will crash. 该程序将崩溃。

The std::vector 's at() function will also be your friend. std::vector的at()函数也将成为您的朋友。

Simply increase array sizes. 只需增加阵列大小即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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