?? cycles
字號:
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 + -