C++ Depth First Search (DFS) Implementation [closed]

邮差的信 提交于 2019-12-07 18:51:40

问题


I am trying to implement the following DFS code described at Competitive Programming 1 book:

#include <cstdio>
#include <vector>
using namespace std;

#define MAX 10
#define DFS_BLACK 1
#define DFS_WHITE -1
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;

vi dfs_num;
vector<vii> adj(MAX);

void dfs(int u) {
    dfs_num[u] = DFS_BLACK;
    for (int i = 0; i < (int)adj[i].size(); i++) {
        ii v = adj[u][i];
        if (dfs_num[v.first] == DFS_WHITE)
            dfs(v.first);
    }
    printf(" %d", u);
}

int main() {
    int v, e, x, y;

    scanf("%d %d", &v, &e);
    for (int i = 0; i < e; i++) {
        scanf("%d %d", &x, &y);
        adj[x].push_back(ii(y, 1));
        adj[y].push_back(ii(x, 1));
    }

    int numCC = 0;
    dfs_num.assign(v, DFS_WHITE);
    for (int i = 0; i < v; i++)
        if (dfs_num[i] == DFS_WHITE)
            printf("Component %d:", ++numCC), dfs(i), printf("\n");
    printf("There are %d connected components\n", numCC);
}

What I am trying to get is:

Input:        Output:
9 7           Component 1: 0 1 2 3 4
0 1           Component 2: 5
1 2           Component 3: 6 7 8
1 3           There are 3 connected components
2 3
3 4
6 7
6 8

For the following graph:

But I am getting "Component 1: 3 2 1" then it crashes. What am I doing wrong?

Any help is appreciated.


回答1:


for (int i = 0; i < (int)adj[i].size(); i++) {

into:

for (int i = 0; i < (int)adj[u].size(); i++) {
//                           ^ u, not i

Live demo link




回答2:


The overall logic seems ok, but I see some weird things in the details:

  1. in line 17, the for-loop, should that be adj[u], rather than adj[i] ??

Other things I noticed:

  1. Not using single-letter variable names would greatly help us understand your code...means you'll get more replies.
  2. Your connected components will print in reverse order (3 2 1, rather than 1 2 3) because in dfs() you have the print after the recursive call
  3. I question why you're using a pair in lines 31 and 32 when the second int is 1, and you never use it.


来源:https://stackoverflow.com/questions/25671618/c-depth-first-search-dfs-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!