定义
//邻接矩阵
typedef struct MGraph{
char vex[MAXSIZE];
int edge[MAXSIZE][MAXSIZE];
int vexnum,edgenum;
}MGraph;
//带权重的邻接矩阵
struct MGraphW{
//储存的顶点表
char vex[MAXSIZE];
//路径矩阵,只不过改成权重了
int weight[MAXSIZE][MAXSIZE];
//存储顶点与边的个数
int vexnum,arcnum;
};
//邻接表
typedef struct ArcNode{
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct VNode{
char value;
ArcNode *first;
}VNode,AdjList[MAXSIZE];
typedef struct{
AdjList vertices;
int vexnum,arcnum;
}ALGraph;
基本操作
//创建邻接矩阵
MGraph createMGraph(){
MGraph G;
scanf("%d,%d",&G.vexnum,&G.edgenum);
for(int i=0;i<MAXSIZE;i++){
scanf("%c",&G.vex[i]); //输入顶点的符号
for(int j=0;j<MAXSIZE;j++){
G.edge[i][j] = 0;
}
}
int v1,v2;
for(int i=0;i<G.edgenum;i++){
scanf("%d,%d",&v1,&v2);
G.edge[v1][v2] = 1;
}
return G;
}
//邻接矩阵求入度
int getInDegreeByMG(MGraph G,int k){
int sum = 0;
for(int i=0;i<G.vexnum;i++){
if(G.edge[i][k]!=0)sum++;
}
return sum;
}
//邻接矩阵求出度
int getOutDegreeByMG(MGraph G,int k){
int sum = 0;
for(int i=0;i<G.vexnum;i++){
if(G.edge[k][i]!=0)sum++;
}
return sum;
}
//邻接矩阵求解有向图的边数
int getEdgeNumInDMG(MGraph G){
int sum = 0;
for(int i=0;i<G.vexnum;i++){
for(int j=0;j<G.vexnum;j++){
if(G.edge[i][j]!=0)sum++;
}
}
return sum;
}
//邻接矩阵创建带权重的有向图
MGraphW createGraphW(){
MGraphW G;
scanf("%d,%d",&G.vexnum,&G.arcnum);
for(int i=0;i<G.vexnum;i++){
scanf("%c",&G.vex[i]); //输入顶点的符号
for(int j=0;j<G.vexnum;j++){
G.weight[i][j] = INF;
}
}
int v1,v2,w;
for(int i=0;i<G.arcnum;i++){
scanf("%d,%d,%d",&v1,&v2,&w);
G.weight[v1][v2] = w;
}
return G;
}
//邻接矩阵创建无向图
MGraph createMGraphWD(){
MGraph G;
scanf("%d,%d",&G.vexnum,&G.edgenum);
for(int i=0;i<G.vexnum;i++){
scanf("%c",&G.vex[i]); //输入顶点的符号
for(int j=0;j<G.vexnum;j++){
G.edge[i][j] = 0;
}
}
int v1,v2,w;
for(int i=0;i<G.edgenum;i++){
scanf("%d,%d",&v1,&v2);
G.edge[v1][v2] = 1;
G.edge[v2][v1] = 1;
}
return G;
}
//邻接矩阵创建带权重的无向图
MGraphW createGraphWD(){
MGraphW G;
scanf("%d,%d",&G.vexnum,&G.arcnum);
for(int i=0;i<G.vexnum;i++){
scanf("%c",&G.vex[i]); //输入顶点的符号
for(int j=0;j<G.vexnum;j++){
G.weight[i][j] = INF;
}
}
int v1,v2,w;
for(int i=0;i<G.arcnum;i++){
scanf("%d,%d,%d",&v1,&v2,&w);
G.weight[v1][v2] = w;
G.weight[v2][v1] = w;
}
return G;
}
//(难)创建邻接表
ALGraph createALGraph(){
ALGraph G;
//p代表前一个结点 q代表工作结点
ArcNode *p,*q;
int n;
scanf("%d,%d",&G.vexnum,&G.arcnum);
for(int i=0;i<G.vexnum;i++){
//输入点的值和此点的边数
scanf("%c,%d",&G.vertices[i].value,n);
for(int j=0;j<n;j++){
//构造弧链表
q = (ArcNode*)malloc(sizeof(ArcNode));
scanf("%d",&q->adjvex);
if(!G.vertices[i].first){
q->next = NULL;
G.vertices[i].first = q;
p = q;
}else{
q->next = NULL;
p->next = q;
p = q;
}
}
p = q = NULL;
}
return G;
}
//邻接表求出度
int getOutDegreeByALG(ALGraph G,int k){
int sum = 0;
ArcNode *p;
p = G.vertices[k].first;
while(p){
sum++;
p = p->next;
}
return sum;
}
//邻接表求入度
int getInDegreeByALG(ALGraph G,int k){
int sum=0;
ArcNode *p;
for(int i=0;i<G.vexnum;i++){
p = G.vertices[i].first;
while(p){
if(p->adjvex == k)sum++;
p = p->next;
}
}
return sum;
}