Description
给定一个图的邻接矩阵,请判断该图是否是连通图。连通图:任意两个顶点之间都有路径。
–程序要求–
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
Input
第1行输入一个整数k,表示有k个测试数据
第2行输入一个整数n,表示有n个结点
从第3行起到第n+2行输入一个邻接矩阵,其中Matrix[i,j]=1表示第i,j个结点之间有边,否则不存在边。
接下来是第2到第k个测试数据的结点数和邻接矩阵
Output
输出Yes or No表示图是否是强连通图
Sample
#0
Input
2 4 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 7 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 1 0
Output
Yes No
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<stack>
using namespace std;
bool isAll(int** martix, int i, int n)
{
int* check = new int[n];
for (int i = 0; i < n; i++)
check[i] = 0;
stack<int> a;
a.push(i);
if (!check[i])
check[i] = 1;
while (!a.empty())
{
int j;
i = a.top();
for (j = 0; j < n; j++)
{
if (martix[i][j] && !check[j])
{
check[j] = 1;
a.push(j);
break;
}
}
if (j == n)
a.pop();
}
for (i = 0; i < n; i++)
if (!check[i])
break;
if (i == n)
return true;
else
return false;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n, flag = 1;
cin >> n;
int** martix = new int*[n];
for (int i = 0; i < n; i++)
martix[i] = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> martix[i][j];
int i;
for (i = 0; i < n; i++)
if (!isAll(martix, i, n))
break;
if (i == n)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}