草草实现的随机图产生器(邻接矩阵)和最短路径算法

本文介绍了如何使用C++实现一个随机图生成器(邻接矩阵表示)以及Dijkstra最短路径算法。代码中包含了图的生成、最短路径计算以及打印图内容的功能。程序通过设置随机种子生成有向图,并确保图中不含自环。Dijkstra算法用于寻找单节点的最短路径。
摘要由CSDN通过智能技术生成

        好久没有实现数据结构算法方面的东西了,前天晚上心血来潮写了这个随机图产生函数并实现了最短路径算法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(&

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值