[英]how to find a pit in a directed graph?
Question : we have a directed graph , how to find a hole (pit) in a graph on Ɵ(n) time complexity . 问题:我们有向图,如何在Ɵ(n)时间复杂度上找到一个孔(凹坑)。
a pit on graph : if an vertex with n-1 degree for (input) and degree 0 for (output) , we have a pit on graph . 图上的凹坑:如果顶点(输入)的n-1度和(输出)度的顶点为0,则在图上有凹坑。
Am I missing something? 我想念什么吗? Don't search the graph following graph edges.
不要在图形边缘之后搜索图形。 Just iterate over all n vertices in the graph and test each one for the number of incoming and outgoing edges.
只需遍历图中的所有n个顶点,并测试每个顶点的入站和出站边数即可。 I assume for each vertex you can store a count of incoming and outgoing edges.
我假设您可以为每个顶点存储入站和出站边的计数。 This would scale O(n), if you have the edge counts.
如果您有边缘计数,则将缩放O(n)。
@REPLY: We'd have to know how your graph is implemented to get more specific. @REPLY:我们必须知道您的图形是如何实现的才能更加具体。 But I mean something like:
但我的意思是:
foreach( node in graph )
if (( node.numberInputEdges == numNodes -1 ) &&
( node.numberOutputEdges == 0 ))
print ( "this node is a pit" )
I don't think you need to search graph at all. 我认为您根本不需要搜索图形。 you can just count indegree and outdegree of every node.
您可以只计算每个节点的度数和度数。 you just have to look for which node- indegree of a node is (n-1) and outdegree is '0'.
您只需要查找节点的哪个节点的度数为(n-1),哪个节点的度数为'0'。
Considering you know "how many edges" are there. 考虑到您知道“有多少条边”。
int outdegree[n]={0}; // Storing outdegree of each node
int indegree[n]={0}; /// Storing indegree of each node
while(m--) // m is number of edges
{
scanf("%d %d",&a,&b); // this means there is an edge from 'a' to 'b'. a-->b
outdegree[a]++;
indegree[b]++;
}
int sink;
for(i=1;i<=n;i++)
{
if((outdegree[i]==0 )&& (indegree[i]==(n-1)))
sink=i;
}
cout<<"Sink/Pit is: "<<sink<<endl;
If you have a adjacency list implementation , just scan it,and you will find in O(n) time,if there is a vertex with outdegree 0. If you have a adjacency matrix, you can use DFS. 如果有邻接表实现,只需对其进行扫描,即可发现O(n)时间中是否存在一个顶点的度数为0。如果有邻接矩阵,则可以使用DFS。
In DFS , just just increment the counter indegree whenver we find a outgoing node. 在DFS中,只要我们发现传出节点,只需增加计数器的度数即可。
A pseudo code : 伪代码:
for each adjacent node :
indegree->neighbour ++;
if (neighbour not visited ) dfs(neighbour)
Finaly scan indegree array to get which node has indegree (n-1) ,bcoz every node will have an edge to the Pit . 最终扫描indegree数组以获取哪个节点具有in度(n-1),bcoz每个节点将具有一个到Pit的边缘。
There can only be one "pit" in a graph (because of the deg_in = N-1). 图中只能有一个“坑”(因为deg_in = N-1)。 So search for all nodes with deg_out = 0. If two, stop.
因此搜索deg_out = 0的所有节点。如果为2,则停止。 If one, check the deg_in.
如果是,请检查deg_in。 This is O(N).
这是O(N)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.