问题 : 求城市间最短通路 . 设有如图所示的 N 座城市 , 相邻城市之间有若干条通路 , 线上的数字表示通路的距离 . 试求出从 A 到 D 的最短距离 .
我们用 MD (v) 表示点 v 到点 D 的最短通路的长度,用 w (v,u) 表示点 v 到点 u 的线段长度 , d (v) 是与 v 相邻的节点的集合。那么根据前面的分析就有:
程序如下:
#include <iostream>
using namespace std;
const int max_array_num = 7;
const int path_init_len = 1000;
const int path_name_len = 10;
using namespace std;
const int max_array_num = 7;
const int path_init_len = 1000;
const int path_name_len = 10;
int MinPathLen[max_array_num] = {0};
int MinPathIndex[max_array_num] = {0};
char PathName[max_array_num][path_name_len] = {"A","B1","B2","C1","C2","C3","D"};
int g_array[max_array_num][max_array_num] = {
{0,5,2,0,0,0,0},
{0,0,0,3,2,0,0},
{0,0,0,0,7,4,0},
{0,0,0,0,0,0,4},
{0,0,0,0,0,0,3},
{0,0,0,0,0,0,5},
{0,0,0,0,0,0,0}
};
void Min_Path(int g_array[max_array_num][max_array_num])
{
int i,j;
int temp = 0;
int MinPathIndex[max_array_num] = {0};
char PathName[max_array_num][path_name_len] = {"A","B1","B2","C1","C2","C3","D"};
int g_array[max_array_num][max_array_num] = {
{0,5,2,0,0,0,0},
{0,0,0,3,2,0,0},
{0,0,0,0,7,4,0},
{0,0,0,0,0,0,4},
{0,0,0,0,0,0,3},
{0,0,0,0,0,0,5},
{0,0,0,0,0,0,0}
};
void Min_Path(int g_array[max_array_num][max_array_num])
{
int i,j;
int temp = 0;
for (i = max_array_num-2; i >=0 ; i--)
{
MinPathLen[i] = path_init_len;
for (j = i + 1;j < max_array_num; j++)
{
if(g_array[i][j])
{
temp = MinPathLen[j] + g_array[i][j];
if(temp < MinPathLen[i])
{
MinPathLen[i] = temp;
MinPathIndex[i] = j;
}
}
}
}
}
int main(int argc,char *argv[])
{
int i = 0;
Min_Path(g_array);
cout<<"MinPathLen="<<MinPathLen[i]<<endl;
{
MinPathLen[i] = path_init_len;
for (j = i + 1;j < max_array_num; j++)
{
if(g_array[i][j])
{
temp = MinPathLen[j] + g_array[i][j];
if(temp < MinPathLen[i])
{
MinPathLen[i] = temp;
MinPathIndex[i] = j;
}
}
}
}
}
int main(int argc,char *argv[])
{
int i = 0;
Min_Path(g_array);
cout<<"MinPathLen="<<MinPathLen[i]<<endl;
cout<<"Path:"<<PathName[i]<<"->";
do
{
cout<<PathName[MinPathIndex[i]]<<"->";
i = MinPathIndex[i];
}while(MinPathIndex[i]!=(max_array_num-1));
{
cout<<PathName[MinPathIndex[i]]<<"->";
i = MinPathIndex[i];
}while(MinPathIndex[i]!=(max_array_num-1));
cout<<PathName[MinPathIndex[i]];
cout<<endl;
return 0;
}
cout<<endl;
return 0;
}