In the figure there are looking for a ring (only find a ring)

In the figure there are looking hoop, two arrays. VISX [i] where i is expressed as a starting point a has been traversed, and the ring is absent. vis [i] indicates the current search tree, the point I has been traversed, so when the second pass to it, the ring can be found.

void dfs(int x)
{
	if( vis[x] == 1 )
	{
		flag = x;    //flag为循环点,回溯时用来加边
		return;
	}
	if( visx[x] == 1 ) return;
	visx[x] = 1;
	vis[x] = 1;
	for (int i = 0; i < g[x].size(); i++)
	{
		int t = g[x][i];
		dfs(t);
		if( flagx ) 
		{
			vis[x] = 0;
			return;
		}
		if( flag )
		{
			e.push_back(edge(x,t));   //存环上的边 
			if( x == flag ) flagx = 1;
			vis[x] = 0;
			return; 
		}
	}
	vis[x] = 0;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n,m;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x,y;
		cin >> x >> y;
		g[x].push_back(y); 
	}
	for (int i = 1; i <= n; i++)
	{
		flag = 0,flagx = 0;
		if( visx[i] == 0 ) dfs(i);
		if( flag ) break;
	}
}
Published 132 original articles · won praise 6 · views 7915

Guess you like

Origin blog.csdn.net/weixin_44316314/article/details/105032984