#include
#include
#include
typedef struct tagGraph
{
unsigned int ulVecNum;
unsigned int ulEdgeNum;
int **pplAdj;
}GraphStru;
typedef struct tagEdge
{
unsigned int ulVec1;
unsigned int ulVec2;
int lDirect;
}EdgeStru;
EdgeStru RandEdge(int ulVecMaxNum)
{
EdgeStru stEdge;
stEdge.ulVec1 = rand() % ulVecMaxNum;
stEdge.ulVec2 = rand() % ulVecMaxNum;
stEdge.lDirect = 0;
return stEdge;
}
void GraphInserEdge(GraphStru *pstGraph, EdgeStru *pstEdge)
{
pstGraph->pplAdj[pstEdge->ulVec1][pstEdge->ulVec2] = 1;
pstGraph->pplAdj[pstEdge->ulVec2][pstEdge->ulVec1] = 1;
}
void GraphShow(GraphStru *pstGraph)
{
int i = 0;
int j = 0;
for(i = 0; i < pstGraph->ulVecNum; i++)
{
for(j = 0; j < pstGraph->ulVecNum; j++)
{
printf("%d ", pstGraph->pplAdj[i][j]);
}
printf("\n");
}
}
void GraphRandEdge(GraphStru *pstGraph, unsigned int ulEdgeNum)
{
int i = 0;
EdgeStru stEdge = {0};
srand(time(NULL));
for(i = 0; i < ulEdgeNum; i++)
{
do
{
stEdge = RandEdge(pstGraph->ulVecNum);
}while(stEdge.ulVec1 == stEdge.ulVec2);
GraphInserEdge(pstGraph, &stEdge);
}
}
GraphStru *GraphInit(unsigned int ulVecNum, unsigned int ulEdgeNum)
{
int i = 0;
GraphStru *pstGraph = malloc(sizeof(*pstGraph));
pstGraph->ulVecNum = ulVecNum;
pstGraph->ulEdgeNum = ulEdgeNum;
pstGraph->pplAdj = (int **)calloc(ulVecNum * sizeof(int*), 1);
pstGraph->pplAdj[0] = (int *)calloc(ulVecNum * ulVecNum * sizeof(int), 1);
for(i = 1; i < ulVecNum; i++)
{
pstGraph->pplAdj[i] = pstGraph->pplAdj[0] + (ulVecNum * i);
}
GraphRandEdge(pstGraph, ulEdgeNum);
return pstGraph;
}
int main()
{
GraphStru *pstGraph = GraphInit(20,80);
GraphShow(pstGraph);
return 0;
}
输出结果:
0 1 1 0 0 0 1 1 1 0 1 0 0 0 1 1 0 1 1 1
1 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0
1 0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1
0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 0 1
0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 0 0 0 0 1
0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0
1 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 1
1 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0
0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 0 0 1 0 0
1 0 1 0 1 0 1 0 0 1 0 1 1 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0
0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 0
0 1 0 1 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0
1 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1
1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0
1 0 1 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0
1 0 0 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0 0 0
1 0 1 1 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0
阅读(1928) | 评论(1) | 转发(0) |