简体   繁体   English

c++中使用class的DFS实现

[英]DFS implementation using class in c++

Please let me know the reason for the error that is coming in the program.请让我知道程序中出现错误的原因。 I was trying to create a graph class and implement printing of elements using dfs.我试图创建一个图形 class 并使用 dfs 实现元素的打印。

The link to the following code is:以下代码的链接是:

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

class graph {
    public:
        int **adj;
        int *visited;
        int n,e;

        graph(int vert, int edges) {
            e = edges;
            n = vert;
            adj = new int*[n];

            for(int i=0; i<n; i++) {
                adj[i] = new int[n];
                for(int j=0; j<n; j++) {
                    adj[i][j] = 0;
                }
            }
            
            visited = new int[n];
            for(int i=0; i<n; i++) {
                visited[i] = 0;
            }

        }

        void inputAdj() {
            for(int i=0; i<e; i++) {
                int l,r;
                cin>>l>>r;
                adj[l][r] = 1;
                adj[r][l] = 1;
            }
        }

        void DFS(int k) {
            cout<<k<<" ";
            visited[k] = 1;
            for(int i=0; i<n; i++) {
                if(k == i) continue;

                if(adj[k][i] == 1) {
                    if(visited[i]) {
                        continue;
                    }
                }

                DFS(i);
            }
        }
        
        ~graph() {
            for(int i=0; i<n; i++) {
                delete[] adj[i];
            }
            delete[] adj;
            delete[] visited;
        }
};

void printDFS(graph *g, int sz) {
    for(int i=0; i<sz; i++) {
        if(!g->visited[i]) {
            g->DFS(i);
        }
    }
}

int main() {

    int n = 7, e = 6;
    // cin>>n>>e;
    graph g(n,e);

    g.inputAdj();

    // int etf;
    // cin>>etf;

    printDFS(&g, n);

    return 0;
}

the input i was giving was:我给出的输入是:

0 1
1 2
2 3
3 4
4 0
5 6

The error that i recieved:我收到的错误:

run: line 1:     3 File size limit exceeded(core dumped) LD_LIBRARY_PATH=/usr/local/gcc-8.3.0/lib64 ./a.out

I think the cause of this error is some sort of infinite loop that is being created here.我认为这个错误的原因是这里创建了某种无限循环。 I am not being able to locate it.我无法找到它。 Please helpp!!请帮忙!!

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

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