好久没有实现数据结构算法方面的东西了,前天晚上心血来潮写了这个随机图产生函数并实现了最短路径算法Dijkstra怀念一下已经远去的大学生活!对于图的生成要注意几个方面1)没有自回路,也就是说邻接矩阵的主对角线元素要全部为0;2)本程序产生的都是有向图,如果是无向图那么这个矩阵是关于对角线对称的,可以通过生成上(下)三角阵然后对称拷贝的方式生成.
比较凌乱,其中一些安全性判断代码可以放到一个函数里让程序看起来更简洁些。
/*********************************************
* File: DIJKSTRA.CPP *
* Author: Lute *
* Date: Jan, 23nd, 2005 *
* Desc: We will provide a impliention *
* of Random Graph Generator and *
* the Dijkstra Algorithm *
*********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //for function memset()
#include <sys/time.h> //for function time(), as random seed. If you are using
//VS6.0, replace it as #include<time.h>
#define INFINITE 1000000
#define ALLKNOWN -2
#define MIN(a, b) (a>b?b:a)
//definition of the node of the graph
struct node{
int id; //the id of the node
int data; //the data store in node
bool known; //is known? reserve for some algorithm
};
typedef struct node Node;
//definition of the Graph structure
struct graph{
int num; //the number of node
Node* gnode; //pointer to the graph node list
int* ajcent; //pointer to the ajacent matrix, and we will store n*n
//edges'infomation in one-dimension array
};
typedef struct graph Graph;
Graph* GenRandGraph(int nodenum)
{
int i;
int adjcentnum = nodenum*nodenum;
//initialize the graph
Graph* graph = NULL;
graph = (Graph*)malloc(sizeof(Graph));
memset(graph, 0, sizeof(Graph));
if(!graph)
{
printf("GenRandGraph 1:Not enough memory to allocate!/n");
return NULL;
}
graph->num = nodenum;
graph->gnode = (Node*)malloc(sizeof(Node)*nodenum);
graph->ajcent = (int*)malloc(sizeof(int)*adjcentnum);
if(!graph->gnode)
{
printf(&