[英]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 我在您的代码中发现了以下错误
#include <bits/stdc++.h>
. #include <bits/stdc++.h>
。 Do not use this header. using namespace std;
Do not use this. vector<int> adj[5];
fo never and under no circumstances use plain C-Style arrays. 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.