题目:
有向图以邻接矩阵存储,试编写图的基本运算(删除一条边、求某个顶点的出度)
实现代码:
#include <iostream>
#include <stdio.h>
using namespace std;
#define INF 32767
#define MAXV 100
typedef char InfoType;
typedef struct
{ int no;
InfoType info;
} VertexType;
typedef struct
{ int edges[MAXV][MAXV];
int n, e;
VertexType vexs[MAXV];
} MatGraph;
void CreateMat(MatGraph &g, int A[MAXV][MAXV], int n, int e)
{ int i, j;
g.n = n;
g.e = e;
for (i = 0; i < g.n; i++)
for (j = 0; j < g.n; j++)
{ if (i == j)
{ g.edges[i][j] = 0;
}
else if (A[i][j] == 0 && i < j)
{ g.edges[i][j] = INF;
g.edges[j][i] = INF;
}
else if (i < j)
{ g.edges[i][j] = A[i][j];
g.edges[j][i] = A[i][j];
}
}
}
void DispMat(MatGraph g)
{ int i, j;
for (i = 0; i < g.n; i++)
{ for (j = 0; j < g.n; j++)
if (g.edges[i][j] != INF)
printf("\t%d", g.edges[i][j]);
else
printf("\t%s", "∞");
printf("\n");
}
}
void DelArc(MatGraph &g, int u, int v)
{ if (g.edges[u][v] == 0)
cout << "此边不存在!" << endl;
else
{ g.edges[u][v] = 0;
g.e--;
}
}
int GetOutdegree(MatGraph &g, int p)
{ int degree = 0;
for (int i = 0; i < g.n; i++)
{ if (g.edges[p][i] == 1)
degree++;
}
printf("结点%d的出度=%d", p, degree);
}
int main()
{ MatGraph g;
int A[MAXV][MAXV] = {{0, 1, 0, 1, 1}, {1, 0, 1, 1, 0},
{0, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {1, 0, 1, 1, 0}
};
int n = 5, e = 8;
CreateMat(g, A, n, e);
cout << "原邻接矩阵:" << endl;
DispMat(g);
GetOutdegree(g, 3);
cout << endl << endl;
DelArc(g, 3, 1);
cout << "删除<3,1>后:" << endl;
DispMat(g);
GetOutdegree(g, 3);
cout << endl;
}