超简单最短距离之深度优先搜索

//最短路径
//例:
//有向图,以下分别表示P1点到P2点的距离
//   P1 | P2 | DIS
//    1    2     2 
//    1    5    10
//    2    3     3
//    2    5     7
//    3    1     4
//    3    4     4
//    4    5     5
//    5    3     3
//step1:将存储图的方法称为图的*邻接矩阵存储法*
//通路为距离大小,不通为-1,自身为0
//      1    2    3    4    5
// 1    0    2   -1   -1   10
// 2   -1    0    3   -1   -1
// 3    4   -1    0    4   -1
// 4   -1    1   -1    0    5
// 5   -1   -1   31   -1    0
//step2:构造邻接表
const int NUM = 100;		//最节点数量
int Sroad[NUM][NUM];		//记录路径距离
int Sbook[NUM];			//记录访问
void SBoundTableSet(int n)	//初始化
	{
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++)
			Sroad[i][j] = (i == j) ?  0 : -1;
	}
void SRoadSet()				//路径设置
	{
		Sroad[1][2] = 2;
		Sroad[1][5] = 10;
		Sroad[2][3] = 3;
		Sroad[2][5] = 7;
		Sroad[3][1] = 4;
		Sroad[3][4] = 4;
		Sroad[4][5] = 5;
		Sroad[5][3] = 3;
	}
void SBookSet(int n)			//未访问的节点设置为true,为了防止重复访问
	{
	for(int i = 1; i <= n; i++)
		Sbook[i] = true;
	}
//v是当前位置,n是终点位置,dis是走过的路程
void Sdfs(int v, int n,int& dis, int& MinLong)		//两点距离最短路径-深度优先搜索
	{
		if(dis > MinLong) return;	//如果走过的路程已经大于之前最短的路径,则直接返回即可
		if(v == n)					//如果已经走到终点,则返回
			{
				if(dis < MinLong) MinLong = dis;
				return;
			}
		for(int i = 1; i <= n ; i++)
			{
				if(Sroad[v][i] != -1 && Sbook[i])
					{
						Sbook[i] = false;		//标记已经被访问
						dis += Sroad[v][i];		//累计路程
						Sdfs(i,n,dis,MinLong);	//访问i节点
						dis -= Sroad[v][i];		//返回上一路径,路程变短
						Sbook[i] = true;		//i重新标记为未访问
					}
			}
		return;
	}
//最短距离:深度优先搜索
void SdfsTest()
	{
		int n = 5, dis = 0,MinLong = 999999;	//节点个数,动态距离,最短距离
		SBoundTableSet(n);						//初始化二维表
		SRoadSet();								//初始化路径
		SBookSet(n);							//记录节访问节点标记
		Sbook[1] = false;						//从节点1(起点)开始搜索
		Sdfs(1,5,dis,MinLong);
		getchar();
	}

猜你喜欢

转载自blog.csdn.net/feengg/article/details/80477784