**
数组表示法建立图,建立邻接矩阵,求顶点的度
要求
**
对给定的任意连通无向图各个结点,使用数组表示法创建该图。其中无向图结点(0,1,3)表示该节点为0,与其相邻的结点为1和3。
创建该图后根据邻接矩阵计算每个结点的度,并输出。
文本输入
input_7_1.txt,每一组数据表示一个图,至少包含3个结点,第一行为节点个数,第二行开始为无向图各个节点的邻接表示,最后一行是空行。以下为例:
4
0 1 3
1 0 2 3
2 1 3
3 0 1 2
文本输出
output_7_1.txt,每一组输入数据对应一行输出数据,按输入结点的数据依次输出各个结点的度,如上述输入对应的输出为
2 3 2 3
如果输入数据有错,则输出ERROR
多组输入数据则对应多行输出结果
源码如下:
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
using namespace std;
#define max 100
#define infinity (~(1<<(sizeof(int)*8-1))) //正无穷
struct graph
{
int Vnum; //顶点数
int edge[max][max]; //边数组
int str[20][20],cou[20];
};
//创建无向图
void creategraph(graph *&g,int &A)
{
int *f=new int, e, i=0, j=0, k,count=0;
char ch, d = 0; string s;
//读文本
ofstream ofile;
ofile.open("output_7_1.txt", ios::out | ios::app);
ifstream ifile("input_7_1.txt", ios::in);
for (int a = 0; a < A;a++)
getline(ifile, s); //因为一共有5组测试,getline清理前面的数据,
//不影响下一组数据的读取
ifile >> noskipws; //不跳过空格,换行,作为判断结束的条件
ifile >>g->Vnum>>ch;
A += g->Vnum;
A++;
//把数据存到二维数组里
for (int a = 0; a < g->Vnum;a++)
{ while (d != '\n'&&!ifile.eof())
{
ifile >> g->str[i][j] >> d;
j++;
count++;
}
g->str[i][j] = '\0';
g->cou[i] = count;
d = 0; count = 0;
i++;
j = 0;
}
for (i = 0; i < g->Vnum; i++)
{
for (j = 0; j < g->cou[i]; j++)
cout << g->str[i][j] << " ";
cout << endl;
}
//对邻接矩阵初始化
for (i = 0; i < g->Vnum; i++)
{
for (j = 0; j < g->Vnum; j++)
{
if (i == j)
g->edge[i][j] = 0;
else
g->edge[i][j] = infinity;
}
}
//建立邻接矩阵
for (i = 0; i < g->Vnum; i++)
{
for (j = 0; j < g->cou[i]; j++)
{
e = g->str[i][j];
for (k = 0; k < g->Vnum; k++)
{
if (g->str[k][0] == e&&k!=i)
{
g->edge[i][k] = 1;
}
}
}
}
//判断是否邻接矩阵对称
int b = 0;
for (i = 0; i < g->Vnum; i++)
{
for (j = 0; j < g->Vnum; j++)
{
if (g->edge[i][j] != g->edge[j][i])
{
ofile << "ERROR" << endl;
exit(0);
system("pause");
}
}
}
ifile.close();
ofile.close();
}
//展示邻接矩阵
void showgraph(graph *&g)
{
cout << "邻接矩阵为:" << endl;
cout << '\t';
for (int i = 0; i < g->Vnum; i++)
cout <<g->str[i][0] << '\t';
cout << endl;
for (int i = 0; i < g->Vnum; i++)
{
cout << g->str[i][0] << '\t';
for (int j = 0; j < g->Vnum; j++)
{
if (g->edge[i][j] == infinity)
cout << "∞" << '\t';
else
cout << g->edge[i][j] << '\t';
}
cout << endl;
}
cout << "--------------------------------" << endl;
}
void add(graph *g)
{
ofstream ofile;
ofile.open("output_7_1.txt", ios::out | ios::app);
int *d=new int,total=0; //记录度的大小
for (int i = 0; i < g->Vnum; i++)
{
for (int j = 0; j < g->Vnum; j++)
{
if (g->edge[i][j] != infinity)
total += g->edge[i][j];
d[i] = total;
}
total = 0;
}
for (int i = 0; i < g->Vnum;i++)
ofile << d[i]<<" ";
ofile << endl;
ofile.close();
}
int main()
{
static int A = 0; //读文本使用来清空前面数据
for (int i = 1; i <=5 ; i++)
{
graph *g = new graph;
creategraph(g, A);
showgraph(g);
add(g);
}
system("pause");
}