私下定义度数向量以查找DAG的所有拓扑排序是什么?

问题描述 投票:0回答:1

[私有地定义indegree向量的重要性是什么?它可能已在alltopologicalSort()函数中定义。

class Graph 
{ 
int V;    // No. of vertices 

// Pointer to an array containing adjacency list 
list<int> *adj; 

// Vector to store indegree of vertices 
vector<int> indegree; 

// A function used by alltopologicalSort 
void alltopologicalSortUtil(vector<int>& res, 
                            bool visited[]); 

public: 
Graph(int V);   // Constructor 

// function to add an edge to graph 
void addEdge(int v, int w); 

// Prints all Topological Sorts 
void alltopologicalSort(); 
}; 

以及它在下面的addge函数中如何工作

void Graph::addEdge(int v, int w) 
{ 
adj[v].push_back(w); // Add w to v's list. 

// increasing inner degree of w by 1 
indegree[w]++; 
} 

使用度数,请在这里解释addEdge函数在减少度数中的作用

void Graph::alltopologicalSortUtil(vector<int>& res, 
                               bool visited[]) 
{ 
// To indicate whether all topological are found 
// or not 
bool flag = false;  

for (int i = 0; i < V; i++) 
{ 
    //  If indegree is 0 and not yet visited then 
    //  only choose that vertex 
    if (indegree[i] == 0 && !visited[i]) 
    { 
        //  reducing indegree of adjacent vertices 
        list<int>:: iterator j; 
        for (j = adj[i].begin(); j != adj[i].end(); j++) 
            indegree[*j]--; 

        //  including in result 
        res.push_back(i); 
        visited[i] = true; 
        alltopologicalSortUtil(res, visited); 

        // resetting visited, res and indegree for 
        // backtracking 
        visited[i] = false; 
        res.erase(res.end() - 1); 
        for (j = adj[i].begin(); j != adj[i].end(); j++) 
            indegree[*j]++; 

        flag = true; 
      } 
     }
 }   

这是查找所有有向无环图的拓扑排序的完整代码的链接https://www.geeksforgeeks.org/all-topological-sorts-of-a-directed-acyclic-graph/

oop c++11 graph
1个回答
0
投票

我从上面与Gupta和kaya3的讨论中得到了答案

Indegree本可以在某些函数中定义的,然后传递给alltopologicalSort()函数作为参考。但是,然后在课堂上对其进行定义将使其更易于处理。

并且由于封装规则,类的数据成员始终保持私有状态

© www.soinside.com 2019 - 2024. All rights reserved.