当前位置:
文档之家› 离散数学之图的矩阵表示及基本运算
离散数学之图的矩阵表示及基本运算
#include <iostream.h>
int** g(int n)
{
int** a, i, j;
a = new int* [n];//分配指针数组
for(i=0; i<n; i++)
a[i] = new int[n];//分配每个指针所指向的数组
for(i=0; i<n; i++)
for(j=0; j<n; j++) a[i][j]=0;
return a;
}
struct M
{
int n;
int isOrient;
int **ele;
};
class Operators
{
public:
void CreateMatrix(M *x);
void CreateMatrix2(M *x, int n, int isOrient);
void Input(M *x);
}
}
void Operators::Show(M *x)
{
int i, j;
if(x->isOrient)
cout<<"The oriented matrix: "<<endl;
o-oriented matrix: "<<endl;
for(i=0;i<x->n;i++)
while(1)
{
cout<<"Input the edge's start-point and end-point, -1 is to finish inputing:";
cin>>i>>j;
if(i==-1 || j==-1) break;
x->ele[i][j]=1;
if(!x->isOrient) x->ele[j][i]=1;
for(i=0;i<x.n;i++)
cout<<i<<":"<<o.deg_out(&x,i)<<" ";
cout<<endl<<"The deg-in for the points"<<endl;
for(i=0;i<x.n;i++)
cout<<i<<":"<<o.deg_in(&x,i)<<" ";
};
void Operators::CreateMatrix2(M *x, int n, int isOrient)
{
x->n=n;
x->isOrient=isOrient;
x->ele=g(x->n);
}
void Operators::CreateMatrix(M *x)
{
int n, isOrient;
}
void Operators::MatrixAdd(M *a, M *b)
{
int i,j;
for(i=0;i<a->n;i++)
for(j=0;j<b->n;j++)
a->ele[i][j]+=b->ele[i][j];
}
void Operators::Maccessibility(M *a, M *Ma)
{
MatrixMultiple(a, &p, &temp);
MatrixAdd(Ma, &p);
}
Show(&p);
Show(Ma);
for(i=0;i<Ma->n;i++)
for(j=0;j<Ma->n;j++)
if(Ma->ele[i][j]) Ma->ele[i][j]=1;
}
void main()
cout<<"Matrix's n=";
cin>>n;
cout<<"Is the graph oriented? 1=yes, 0=no :";
cin>>isOrient;
CreateMatrix2(x, n, isOrient);
}
void Operators::Input(M *x)
{
int i, j;
{
Operators o;
M x, y;
o.CreateMatrix(&x);
o.CreateMatrix2(&y, x.n, x.isOrient);
o.Input(&x);
o.Show(&x);
int i;
cout<<endl<<"The deg-out for the points"<<endl;
{
for(j=0;j<x->n;j++) cout<<x->ele[i][j]<<" ";
cout<<endl;
}
}
int Operators::deg_out(M *x, int i)
{
int deg=0;
for(int j=0; j<x->n; j++)
if(x->ele[i][j]) deg++;
return deg;
}
int Operators::deg_in(M *x, int i)
{
int deg=0;
for(int j=0; j<x->n; j++)
if(x->ele[j][i]) deg++;
return deg;
}
void Operators::MatrixMultiple(M *a, M *b, M *temp)
void Show(M *x);
int deg_out(M *a, int i);
int deg_in(M *a, int i);
void Maccessibility(M *a, M *Ma);
void MatrixMultiple(M *a, M *b, M *m);
void MatrixAdd(M *a, M *b);
{
int i,j,k;
for(i=0;i<a->n;i++)
for(j=0;j<b->n;j++)
for(k=0;k<a->n;k++)
temp->ele[i][j]+=a->ele[i][k]*b->ele[k][j];
for(i=0;i<a->n;i++)
for(j=0;j<b->n;j++)
b->ele[i][j]=temp->ele[i][j];
cout<<endl;
o.Maccessibility(&x, &y);
o.Show(&y);
}
{
int i,j;
M p, temp;
CreateMatrix2(&p, a->n, a->isOrient);
CreateMatrix2(&temp, a->n, a->isOrient);
MatrixAdd(&p, a);
MatrixAdd(Ma, a);
for(i=0; i<=a->n; i++)
实验四
实验目的
学习图在计算机中的矩阵表示,并能利用课堂所学知识进行出度和入度的计算。
实验内容与要求
根据输入的整数对,输出一个图形的邻接矩阵。并求出各结点的出度和入度。
实验准备
图可以用多种方式来表示,其中邻接矩阵是一种较简单的方式。复习关于邻接矩阵的描述。明确一下内容:
1.如何使用邻接矩阵表示图。
2.利用图的邻接矩阵求结点的出度和入度的方法。