# 有向图邻接矩阵

xiaoxiao2021-02-28  21

#include <stdio.h> #include <stdlib.h> #define MAX_VALUE 8888 //初始化数组的默认值，相当于无限大 #define MAX_POINT_NUM 10 //最大顶点数 typedef int matrix[MAX_POINT_NUM][MAX_POINT_NUM]; //定义有向图的邻接矩阵的结构体 typedef struct { int vertex[MAX_POINT_NUM];//储存顶点的数组 matrix vertex_matrix;//二维数组 int vertex_num;//顶点数 int arc_num;//边数 }digraph; int locatevertex(digraph * graph,int v) { int i; for(i=0;i<graph->vertex_num;i++) { if(graph->vertex[i]==v) { return i; } } return -1; } void init_digraph(digraph * graph) { printf("please input vertex and arc:\n");//输入顶点和边数 scanf("%d%d",&(graph->vertex_num),&(graph->arc_num)); int i; printf("please input vertex point value:\n");//输入顶点的编号 for(i=0;i<graph->vertex_num;i++) { scanf("%d",&graph->vertex[i]); } int j; i=0; for(i=0;i<graph->vertex_num;i++) { for(j=0;j<graph->vertex_num;j++) { graph->vertex_matrix[i][j]=MAX_VALUE;//统一初始化存放顶点间权重值 } } int v1,v2; int weight; printf("please input between arc two point and weight:\n"); //输入两个顶点及他们之间的权重值 int k; for(k=0;k<graph->arc_num;k++) { scanf("%d%d%d",&v1,&v2,&weight); i=locatevertex(graph,v1); j=locatevertex(graph,v2); graph->vertex_matrix[i][j]=weight; } } //打印有向图的邻接矩阵 void print_digraph(digraph * graph) { int i,j; for(i=0;i<graph->vertex_num;i++) { for(j=0;j<graph->vertex_num;j++) { if(graph->vertex_matrix[i][j]==MAX_VALUE) { printf("N\t"); } else { printf("%d\t",graph->vertex_matrix[i][j]); } } printf("\n"); } } int main(int argc,const char *argv[]) { digraph graph; init_digraph(&graph); print_digraph(&graph); return 0; }