您的位置:首页 > 其它

最短路径(Dijikstra和Floyed)

2014-04-01 16:07 363 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

typedef unsigned int ssize_t;

const ssize_t MAXSIZE = 20;

static ssize_t  graph  [MAXSIZE][MAXSIZE];
static ssize_t  node_num;
static char 	node   [MAXSIZE];

#define FLOYED

#ifdef DIJIKSTRA

static ssize_t 	dist   [MAXSIZE];
static char 	path   [MAXSIZE];
static bool 	visited[MAXSIZE];

void find_path_from(char node)
{
ssize_t i = 0, j = 0;
ssize_t start_index = node - 'A';
ssize_t cur_min_path = 0;
char cur_start_index = 0;

visited[start_index] = true;

for(i = 0; i < node_num - 1; i++)
{
if(graph[start_index][i] < UINT_MAX)
dist[i] = graph[start_index][i];
else
dist[i] = UINT_MAX;
}
path[start_index] = 'A' + start_index;
dist[start_index] = 0;

for(j = 0; j < node_num; j++)
{
cur_min_path = UINT_MAX;
for(i = 0; i < node_num; i++)
{
if((visited[i] == false)
&& (dist[i] < cur_min_path))
{
cur_min_path = dist[i];
cur_start_index = i;
}
}
visited[cur_start_index] = true;

for(i = 0; i < node_num; i++)
{
if((visited[i] == false) &&
(dist[i] > dist[cur_start_index] + graph[cur_start_index][i]))
{
dist[i] = dist[cur_start_index] + graph[cur_start_index][i];
path[i] = cur_start_index + 'A';
}
}
}
}

#endif

#ifdef FLOYED

void floyed()
{
int k = 0, i = 0, j = 0;
for(k = 0; k < node_num; k++)
{
for(i = 0; i < node_num; i++)
{
for(j = 0; j < node_num; j++)
{
if(graph[i][j] > graph[i][k] + graph[k][j])
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}

#endif

int
main(ssize_t argc, char * argv [ ])
{
ssize_t i = 0, j = 0;

ssize_t edge_num = 0;
ssize_t distance = 0;
char start_node, end_node;

#ifdef DIJIKSTRA
memset(graph, 0xFF, MAXSIZE * MAXSIZE * sizeof(ssize_t));
memset(dist, 0xFF, MAXSIZE * sizeof(ssize_t));
#endif

printf("请输入节点数量(小于%d):", MAXSIZE);
scanf("%u", &node_num);

for(i = 0; i < node_num; i++)
node[i] = 'A' + i;

printf("节点编号已自动分配为:%c-%c。\n", 'A', node[node_num - 1]);

printf("请输入边的数量:");
scanf("%u", &edge_num);

while(getchar()!='\n');
for(i = 0; i < edge_num; i++)
{
printf("请输入第%d条边(如'A-B:20'):", i + 1 );
scanf("%c-%c:%u",&start_node, &end_node, &distance);
graph[start_node - 'A'][end_node - 'A'] = distance;
graph[end_node - 'A'  ][start_node - 'A'] = distance;
while(getchar()!='\n');
}

#ifdef DIJIKSTRA
find_path_from('A');

for(i = 0; i < node_num; i++)
{
printf("%c->%c:%u\n", 'A', node[i], dist[i]);
}
#endif

#ifdef FLOYED
floyed();
for(i = 0; i < node_num; i++)
{
printf("%c->%c:%u\n", 'A', node[i], graph[0][i]);
}
#endif

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: