有向赋权图的实现
#include <iostream>
#include <stdio.h>
#include <malloc.h>
#define Matrix int
typedef enum {OK=1,ERROR=0,OverFlow=-2} Status;
typedef enum { True = 1, False = 0 } Bool;
/*
Graph(V,W) V为顶点的集合,W为边的集合
Matrix representation of graph 图的矩阵表示
*/
typedef struct _matrixgraph {
int v;
int e;
Matrix **matrix;
}MatrixGraph,*MG;
Matrix** newMatrix(int n);
Bool edgeExist(MG mg, int i, int j);
MG initMatrixGraph(int v);
Status addDirectedEdge(MG mg, int i, int j, int weight = 1); //默认权值为1
Status deleteDirectedEdge(MG mg, int i, int j);
Status printMatrix(MG mg);
int main() {
MG mg = initMatrixGraph(10);
addDirectedEdge(mg, 0, 0);addDirectedEdge(mg, 0, 1);addDirectedEdge(mg, 0, 3);addDirectedEdge(mg, 0, 4);addDirectedEdge(mg, 0, 9);
addDirectedEdge(mg, 5, 0); addDirectedEdge(mg, 5, 1); addDirectedEdge(mg, 5, 3); addDirectedEdge(mg, 5, 4); addDirectedEdge(mg, 5, 9);
addDirectedEdge(mg, 8, 0); addDirectedEdge(mg, 8, 1); addDirectedEdge(mg, 8, 3); addDirectedEdge(mg, 8, 4); addDirectedEdge(mg, 8, 9);
addDirectedEdge(mg, 9, 0); addDirectedEdge(mg, 9, 1); addDirectedEdge(mg, 9, 3); addDirectedEdge(mg, 9, 4); addDirectedEdge(mg, 9, 9);
printMatrix(mg);
free(mg);
system("pause");
return 0;
}
Status printMatrix(MG mg) {
int length = mg->v;
for (int i = 0; i < length; i++) {
for (int j = 0; j < 10; j++) printf(" %d ", mg->matrix[i][j]);
printf("\n");
}
return OK;
}
MG initMatrixGraph(int v) {
MG mg = (MG)malloc(sizeof(MatrixGraph));
mg->v = v;
mg->e = 0;
mg->matrix = newMatrix(v);
return mg;
}
//有向赋权图添加 默认权值为1
Status addDirectedEdge(MG mg, int i, int j, int weight = 1) {//c中没有默认参数
if (i < 0 || j < 0) return ERROR;
if (!edgeExist(mg, i, j)) mg->matrix[i][j] = weight;
else printf("martrix[%d][%d] is exitst\n", i, j);
return OK;
}
Status deleteDirectedEdge(MG mg, int i, int j) {
if (i < 0 || j < 0) return ERROR;
if (edgeExist(mg, i, j)) mg->matrix[i][j] = 0;
else printf("martrix[%d][%d] isn't exitst\n", i, j);
return OK;
}
Bool edgeExist(MG mg, int i, int j) {
if (mg->matrix[i][j] != 0) return True;
return False;
}
Matrix** newMatrix(int n) {
int **matrix = (int **)malloc(n * sizeof(int*));
for (int i = 0; i < n; i++) matrix[i] = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) matrix[i][j] = 0;
return matrix;
}
无向赋权图需修改addEdge,deleteEdge
//无向赋权图添加
Status addUndirectedEdge(MG mg, int i, int j, int weight = 1) {
if (i < 0 || j < 0) return ERROR;
if (!edgeExist(mg, i, j) && !edgeExist(mg, j, i)) {
mg->matrix[i][j] = weight;
mg->matrix[j][i] = weight;
}
else printf("The Edge is exitst between %d and %d \n", i, j);
return OK;
}
Status deleteUndirectedEdge(MG mg, int i, int j, int weight = 1) {
if (i < 0 || j < 0) return ERROR;
if (edgeExist(mg, i, j) && edgeExist(mg, j, i)) {
mg->matrix[i][j] = 0;
mg->matrix[j][i] = 0;
}
else printf("The Edge isn't exitst between %d and %d \n", i, j);
return OK;
}