问题 B: 连通图

题目描述

给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。

输入

每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。如果 n 为 0 表示输入结束。随后有 m 行数据,每行有两个值 x 和 y(0<x, y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。

输出

对于每组输入数据,如果所有顶点都是连通的,输出"YES",否则输出"NO"。

样例输入

4 3
4 3
1 2
1 3
5 7
3 5
2 3
1 3
3 2
2 5
3 4
4 1
7 3
6 2
3 1
5 6
0 0

样例输出

YES
YES
NO
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX_SIZE 1005
using namespace std;
int n, m;
vector<int> linklist[MAX_SIZE];
bool visited[MAX_SIZE] = {false};
void dfs(int now)
{
    visited[now] = true;
    for (int i = 0; i < (int)(linklist[now].size()); i++)
    {
        if (!visited[linklist[now][i]])
        {
            dfs(linklist[now][i]);
        }
    }
}
void init()
{
    for (int i = 0; i < MAX_SIZE; i++)
    {
        linklist[i].clear();
        visited[i] = false;
    }
}
int main()
{
    int index, i, j, res;
    while (cin >> n >> m && n != 0)
    {
        res = 0;
        for (index = 1; index <= m; index++)
        {
            cin >> i >> j;
            if (i != j)
            {
                linklist[i].push_back(j);
                linklist[j].push_back(i);
            }
            else
            {
                linklist[i].push_back(j);
            }
        }
        for (index = 1; index <= n; index++)
        {
            if (!visited[index])
            {
                ++res;
                dfs(index);
            }
        }
        if(res == 0 && n == 1){
            cout << "YES" << endl;
        }
        else if (res == 1)
        {
            cout << "YES" << endl;
        }
        else
        {
            cout << "NO" << endl;
        }
        // cout << res << endl;
        init();
    }
    return 0;
}
/**************************************************************
    Problem: 1908
    User: morizunzhu
    Language: C++
    Result: 正确
    Time:0 ms
    Memory:2048 kb
****************************************************************/

猜你喜欢

转载自blog.csdn.net/Morizunzhu/article/details/81556669