Dijkstra算法 初探

今天看书新学的Dijkstra算法,可以用来计算带权值的无环有向图中单源最短距离。

下面是刚刚写的初版代码= =


// 20151118_Dijkstra.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <list>
using namespace std;

class point
{
public:
	int targetlist[100];
	int targetdistance[100];
	int targetlist_max;
	point()
	{
		targetlist_max = 0;
	}
};

point site[100];
int site_max = 0;

int loadmap(const char* filename)
{
	FILE* fp = fopen(filename, "r");
	if (fp == NULL)
	{
		throw "NOOOOO";
		return -1;
	}
	int all;//点的总数
	fscanf(fp, "%d", &all);
	site_max = all;
	for (int i = 1;i <= all;i++)
	{
		int target_all;//下行点总数量
		fscanf(fp, "%d", &target_all);
		site[i].targetlist_max = target_all;
		for (int j = 0;j < target_all;j++)
		{
			int target_point, target_distance;//下行点和下行距离
			fscanf(fp, "%d %d", &target_point, &target_distance);
			site[i].targetdistance[j] = target_distance;
			site[i].targetlist[j] = target_point;
		}
	}
	fclose(fp);
	return 0;
}


bool known[100];
bool have_distance[100];
int dis[100];
int lastpoint[100];

list<int> todolist;
void findmintrace(int startpoint)
{
	//初始化
	memset(known, false, sizeof(bool) * 100);
	memset(have_distance, false, sizeof(bool) * 100);
	memset(dis, 0, sizeof(int) * 100);
	memset(lastpoint, 0, sizeof(int) * 100);
	todolist.clear();
	//开始
	todolist.push_back(startpoint);
	for (int knowni = 0;knowni < site_max;knowni++)
	{
		int currentpoint = todolist.front();
		//轮询到这个点,这个点就是已知的
		known[currentpoint] = true;
		todolist.pop_front();
		for (int j = 0;j < site[currentpoint].targetlist_max;j++)
		{
			if (known[site[currentpoint].targetlist[j]])
			{
				//如果这个点是已知的
				continue;
			}
			else
			{
				if (have_distance[site[currentpoint].targetlist[j]])
				{
					//以前曾经计算过路程,现在只进行比较
					if (dis[site[currentpoint].targetlist[j]]>dis[currentpoint] + site[currentpoint].targetdistance[j])
					{
						//比较后发现原来的距离比较大,所以用新的替换掉
						dis[site[currentpoint].targetlist[j]] = dis[currentpoint] + site[currentpoint].targetdistance[j];
						//给这个点造成影响的是现在的这个点
						lastpoint[site[currentpoint].targetlist[j]] = currentpoint;
					}
					//如果路程更大的话就算了...
				}
				else
				{
					//以前没计算过路程
					//设置为计算过
					have_distance[site[currentpoint].targetlist[j]] = true;
					dis[site[currentpoint].targetlist[j]] = dis[currentpoint] + site[currentpoint].targetdistance[j];
					lastpoint[site[currentpoint].targetlist[j]] = currentpoint;
				}
				//无论如何这个点都是未知的,所以把这个点放到队列里面
				todolist.push_back(site[currentpoint].targetlist[j]);
			}
		}
	}
}

void showtrace(int endpoint)
{
	if (lastpoint[endpoint]!=0)
	{
		showtrace(lastpoint[endpoint]);
		printf(" to ");
	}
	printf("BLOCK(%d) ", endpoint);
}

int main()
{
	loadmap("map.txt");
	findmintrace(1);
	showtrace(7);
    return 0;
}

^_^ 一会儿稍微优化一下然后包装起来留着解决地图问题ww

你可能感兴趣的:(Dijkstra算法 初探)