说明
用C编写程序以使用邻接矩阵实现图 技术。向用户询问节点和边的数量。然后要求 节点标签,边缘标签。最后询问源节点和目标节点 每个。根据输入,您需要构造图形并 执行以下操作。
- 如果用户输入节点标签,则应该 输出该节点的进出度。
- 如果用户输入边缘 标签,它应该输出其源节点和目标节点。
- 如果用户 输入一个节点标签,它应该输出该节点的所有入射边 节点。
#include <stdio.h>
#define m 50
int ad_mat[m][m];
int n;
int graph(void){
int i, j, source, destination, nd, edge, in_deg, out_deg;
printf("Enter number of nodes:");
scanf("%d", &n);
printf("\n Enter the lables for nodes:");
for (i = 1; i <= n; i++) {
scanf("%d", &nd);
}
printf("\n Enter the number of edges:");
scanf("%d", &edge);
int edgear[edge];
printf("\n Labling edges");
for (i = 1; i <= edge; i++) {
scanf("%d", &edgear[i]);
printf("\n");
}
//labling the edges
for (i = 1; i <= edge; i++) {
printf("\nEnter the source and destination for node %d:", edgear[i]);
scanf("%d %d", &source, &destination);
if ((source) == 0 && (destination) == 0) {
break;
}
if (source > n || destination > n || source <= 0 || destination <= 0) {
printf("\nInvalid edge!");
i--;
}
else{
ad_mat[source][destination] = 1;
}
}
//print adjacency matric
printf("\n adjacency matrix for directed graph\n");
for (i =1; i <= n; i++) {
for (j = 1; j <= n; j++) {
printf("%4d", ad_mat[i][j]);
}
printf("\n");
}
//For in-degree and out-degree
for (i = 1; i <= n; i++) {
in_deg = out_deg =0;
for (j =1; j <= n; j++) {
if (ad_mat[j][i] == 1) {
in_deg++;
}
}
for (j = 1; j <= n; j++) {
if (ad_mat[i][j] == 1) {
out_deg++;
}
}
}
return 0;
}
/*int display(){
int i,j;
for (i =1; i <= n; i++) {
for (j = 1; j <= n; j++) {
printf("%4d", ad_mat[i][j]);
}
printf("\n");
}
return 0;
}*/
int main(int argc, const char * argv[]) {
graph();
// display();
return 0;
}