⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cycles

📁 Write a program to decide if a graph has a cycle or not. The given graph can be a directed or undire
💻
字号:
Cycles in Graphs. Write a program to decide if a graph has a cycle or not. The given graph can be a directed or undirected graph, which is indicated at the time of reading the input (0 for directed graph and 1 for undirected graphs). The input is given as an adjacency list. Higher credit will be given for programs that have optimizations.
Input:
0
3
0 1 1
0 0 1
0 0 0
Output:
No

solution

#include<stdio.h>
#define MAX 1000
int s[MAX],top=-1;
void push(int a)
{
	if(top==MAX-1)
	{
		printf("overflow");
		return;
	}
	s[++top]=a;
}
int pop()
{
	if(top==-1)
	{
		printf("underflow");
		return;
	}
	return(s[top--]);
}
int isempty()
{
	if(top==-1)
		return 1;
	else return 0;
}

int main()
{
	int a,n,i,j,p,adj[1000][1000],visited[1000],flag=0;
	scanf("%d",&a);
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		for(j=1;j<=n;j++)
			scanf("%d",&adj[i][j]);
	i=1;
	push(i);
	visited[i]=1;
	if(a==0)
		while(!isempty())
		{
			p=pop();
			for(j=1;j<=n;j++)
			{
				if(adj[p][j]==1)
				{
					if(visited[j]==1)
					{
						flag=1;
						break;
					}
					if(visited[j]!=1)
					{
						push(j);
						visited[j]=1;
					}
				}
			}
		}
	else if(a==1)
		while(!isempty())
		{
			p=pop();
			for(j=p;j<=n;j++)
			{
				if(adj[p][j]==1)
				{
					if(visited[j]==1)
					{
						flag=1;
						break;
					}
					if(visited[j]!=1)
					{
						push(j);
						visited[j]=1;
					}
				}
			}

		}
	if(flag==1)
		printf("YES");
	else 
		printf("NO");
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -