#define MAX 20 //最大顶点数量
#define MAXLEN 99999999 //最长路径
int book[MAX] = {0}; //标记该城市是否已经在路径中
int map[MAX][MAX] = {0};//邻接矩阵存储两城市间路程
int min = MAXLEN; //城市间最短距离
int sum = 0;
int DeepSearchWay_1(int n, int startPos, int endPos);//深度优先搜索最短路径驱动程序
void dfs(int n, int curPos, int endPos, int dis);//深度优先搜索最短路径子程序
int DeepSearchWay_2(int n, int startPos, int endPos);//深度优先搜索最短路径非递归算法
int Dijkstra(int n, int startPos, int endPos);//Dijkstra最短路径算法
int bfs(int n, int startPos, int endPos);//改进的广度优先搜索最短路径算法
int Floyd(int n, int startPos, int endPos);//Floyd-Warshall最短路径算法
int Floyd2(int n, int startPos, int endPos);//Floyd-Warshall最短路径算法(原始版)
int Bellman(int n, int startPos, int endPos);//Bellman-Fort最短路径算法
int main()
{
int i, j, m, n, a, b, c;
int startPos, endPos;
int DeepSearchWay_1(int n, int startPos, int endPos)//深度优先搜索最短路径驱动程序
{
int i;
for (i=0; i<n; i++)
book[i] = 0;
sum = 0;
min = MAXLEN; //城市间最短距离
book[startPos] = 1;
dfs(n, startPos, endPos, 0);
printf("搜索次数为 %d\n", sum);
return min;
}
void dfs(int n, int curPos, int endPos, int dis)//深度优先搜索最短路径子程序
{
int i;
if (dis > min) //当前路程已大于最短路程,直接返回
return ;
if (curPos == endPos)
{
if (dis < min)
min = dis;
return ;
}
for (i=0; i<n; i++)
{
if (book[i] == 0 && map[curPos][i] != MAXLEN)
{
book[i] = 1;
dfs(n, i, endPos, dis+map[curPos][i]);
book[i] = 0;
}
sum++;
}
}
int DeepSearchWay_2(int n, int startPos, int endPos)//深度优先搜索最短路径非递归算法
{
int Vex[MAX] = {0};
int Stack[MAX] = {0};
int Dis[MAX] = {0};
int i, cur, top = 0;
int sum = 0;
for (i=0; i<n; i++)
book[i] = 0;
for (i=0; i<n; i++)
Dis[i] = map[startPos][i];
Stack[top] = startPos;
book[startPos] = 1;
while (top >= 0)
{
if (Vex[top] < n)
{
i = Vex[top];
cur = Stack[top];
if (book[i] == 0 && map[cur][i] != MAXLEN)
{
if (Dis[i] > Dis[cur] + map[cur][i]) //对各条边进行松弛
{
Dis[i] = Dis[cur] + map[cur][i];
}
int Bellman(int n, int startPos, int endPos)//Bellman-Fort最短路径算法
{
int i, j, m = 0;
int Dis[MAX] = {0};
int u[MAX*MAX] = {0};
int v[MAX*MAX] = {0};
int w[MAX*MAX] = {0};
int sum = 0;
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
if (i != j && map[i][j] != MAXLEN)
{
u[m] = i;
v[m] = j;
w[m++] = map[i][j];
}
}
}
for (i=0; i<n; i++)
Dis[i] = map[startPos][i];
for (i=1; i<n; i++) //只需调整n-1次
{
for (j=0; j<m; j++)
{
if (Dis[v[j]] > Dis[u[j]] + w[j])
{
Dis[v[j]] = Dis[u[j]] + w[j];
}
sum++;
}
}