如何将二维数组作为函数的参数传递[2]

[入库:2005年8月19日] [更新:2007年3月25日]

本文简介:选择自 jatix 的 blog

     //你有一个图的邻接矩阵如adjoinmatrix[n][n]和数组

path[n], length[n](n为图顶点的个数,
     //然后你可以如下调用:shortestpath(adjoinmatrix,

length, path, 5, 0);
     //调用后,path[n]中存放最短路径,length[n]中存放着最

短路径的长度
     //下面的例子中我们求得从0顶点到其他定点的最短路经及

其长度
    
    float adjoinmatrix[5][5]=
    {
    {0, 10,no_path,30,100},
    {no_path,0,50,no_path,no_path},
    {no_path,no_path,0,no_path,10},
    {no_path,no_path,20,0,60},
    {no_path,no_path,no_path,no_path,0}
    };
    int path[5];
    float length[5];
    
      shortestpath(adjoinmatrix, length, path, 5,

0);
     
     int i = 0, int v =0;
     for(i = 1; i < 5; i++)
     {
     v = i;
     while(v != 0)
     {
     printf("%d ", v);
     v = path[v];
     }
     printf("%d\n", v);
     }
     
 --*/
 
 int shortestpath(
  in  float **adjoinmatrix,  //存放图的邻接矩阵,是

一个二维数组
  out float *length,    //用于返回到各

个点的最短路经的长度
  out int   *path,    //用于返回最短

路经,path[i]表示在最短路经上顶点i前面的顶点
  in  int   vertexnum,   //顶点的个数
  in  int   vertex    //起始顶点
  );
 #endif


  //
  // shortestpath.c 中实现了求一个图中某个顶点到其他顶点的最短路经的函数。
  //
 
 #include "shortestpath.h"
 
 #include <stdlib.h>
 
 
 /*++
 abstract:
 该函数的功能是求得一个图中的某个顶点到其他所有顶点的最短路经,及其最短

路经的长度
 returen value:
 类型是int,含义如下
 0 成功
 1   资源不够
 --*/
 
 int shortestpath(
  in  float **adjoinmatrix,  //存放图的邻接矩阵,是

一个二维数组
  out float *length,    //用于返回到各

个点的最短路经的长度
  out int   *path,    //用于返回最短

路经,path[i]表示在最短路经上顶点i前面的顶点
  in  int   vertexnum,   //顶点的个数
  in  int   vertex    //起始顶点
  )
 {
  int i = 0, j = 0, w = 0;
  
  //
  // 已经在最短路经中的点的集合,如果vertexset[i]不为0,则表示第

i个点在该集合中
  //
  int *vertexset = (int*)malloc(vertexnum);
  if(vertexset == null)
  {
   return 1; //缺乏内存资源
  }
  
  //
  // 初始化
  //
  for(i = 0; i < vertexnum; i++)
  {
   length[i] = *((float*)adjoinmatrix + vertex*vertexnum

+ i);
   vertexset[i]=0; 
   if(i != vertex && length[i] < no_path)
   {
    path[i]=vertex;
   }
   else
   {
    path[i] = -1;
   } 
  }
  vertexset[vertex] = 1;
  length[vertex] = 0;
  
  //
  // 求得最短路经
  //
  for(i = 0; i < vertexnum-1; i++)
  {
   float min = no_path;
   int u = vertex;
   for(j = 0; j < vertexnum; j++)
   {
    if( !vertexset[j] && length[j] < min)
    {
     u = j;
     min = length[j];
    }
   }
   vertexset[u] = 1;
   for(w = 0; w < vertexnum; w++)
   {
    if(!vertexset[w] && *((float*)adjoinmatrix +

u*vertexnum + w) < no_path && length[u]+*((float*)adjoinmatrix + u*vertexnum +

w) < length[w])
    {
     length[w] = length[u] +

*((float*)adjoinmatrix + u*vertexnum + w);
     path[w] = u;

本文关键:如何将二维数组作为函数的参数传递
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top