ACM乐园
Love Me,Love My Code!
posts - 53,  comments - 24,  trackbacks - 0
前面有用并查集判断无向图是否有环,这次用dfs来判断是否有环。
图只有树边和反向边,如果有反向边那么就有环,否则就是树或森林。
#include <iostream>

using namespace std;

const int M=501;
bool  g[M][M];
bool  visit[M];
bool  flag;
int   v,e;

bool dfs(int i,int pre)
{
    visit[i]
=true;
    
for(int j=1;j<=v;j++)
        
if(g[i][j])
        
{
            
if(!visit[j])
                
return dfs(j,i);
            
else if(j!=pre)  //如果访问过,且不是其父节点,那么就构成环
                return false;
        }

}


int main()
{
    
int i,j;
    
while(cin>>v>>e)
    
{
        memset(g,
0,sizeof(g));
        
while(e--)
        
{
            cin
>>i>>j;
            g[i][j]
=g[j][i]=true;
        }

        memset(visit,
0,sizeof(visit));
        flag
=dfs(1,0);
        
if(flag)
            cout
<<"no\n";
        
else
            cout
<<"yes\n";
    }

    
return 0;
}


posted on 2011-09-13 11:50 大大木马 阅读(7498) 评论(1)  编辑 收藏 引用

FeedBack:
# re: 判断无向图是否有环dfs
2013-09-18 12:50 | Parallel
There are so many bugs in your code.
i.e.
1. how can you traverse a graph with more than 1 components?
2. how can you deal with the node which has been visited and not pre? Does that means a cycle? No!  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2011年9月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

常用链接

留言簿(1)

随笔档案(53)

文章档案(2)

搜索

  •  

积分与排名

  • 积分 - 62343
  • 排名 - 353

最新评论

阅读排行榜

评论排行榜