微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

程序因异常输出而中止,计算图中的不可达节点

如何解决程序因异常输出而中止,计算图中的不可达节点

我刚刚实现了dfs算法,并想尝试一个问题。问题如下:

输入格式

第一行由2个整数N和M组成,表示该图中节点和边的数量。接下来的M行由2个整数a和b组成,表示节点a和b之间的无向边。下一行由一个整数x表示头节点的索引。

输出格式

您需要打印一个整数,该整数表示从给定的根节点无法访问的节点数。

测试用例输入如下:

10 10
8 1
8 3
7 4
7 5
2 6
10 7
2 8
10 9
2 10
5 10
2

test case and constraints

在这种情况下的输出是:

0

我写的代码

        #include<iostream>
    #include<list>
    #include<queue>
    using namespace std;
    int mycount = 0;
    //Adj List Implementation for Integer Nodes
    class Graph {
    private:
        int V;
        
        //Array of Linked Lists of size V,V LL's are there
        list<int>* adjList;
        int* visited;
    
    public:
        Graph(int v) {
            V = v;
           
            adjList = new list<int>[V];
            visited = new int[V] { 0 };
        }
        void addEdge(int u,int v,bool bidir = true)
        {
            adjList[u].push_back(v);
            if (bidir) {
                adjList[v].push_back(u);
            }
        }
    
    
        int dfs(int vertex)
        {
            visited[vertex] = true;
            mycount++;
    
            for (auto node : adjList[vertex]) {
                if (!visited[node]) {
                    dfs(node);
                }
    
            }
            return mycount;
    
        }
    
    
    
    
    };
    
    
    
    int main() {
        //taking input of number of nodes and edges
        int inputNode,inputEdge;
        cin >> inputNode >> inputEdge;

    //graph object
        Graph g(inputNode);
//taking input
        for (int i = 0; i < inputEdge; i++) {
            int u,v;
            cin >> u >> v;
            g.addEdge(u,v);
        }
        int index;
        cin >> index;
        //run the dfs on index
        int reachabeNodes = g.dfs(index);
    
        cout << inputNode - reachabeNodes;
    
    
    
    
    
    
    
        return 0;
    }

我的代码没有执行后,我看到了其他代码,但是发现它们使用与我的几乎相同的逻辑,

  • 我已经声明了一个全局 mycount 变量,每次调用DFS时该变量都会递增,以便它存储已连接并可以访问的边的数量
  • 接下来,我打印输入中给出的总节点的减法-mycount 请帮助我解决问题的地方。

解决方法

您应该使用列表向量,而不是指向列表数组的指针,并使用向量而不是数组。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。