如图,百度地图上有5个地点,各个地点间是单向的路径,试求出从1到5的最短路径。

从图中可以得到一个5*5的二维矩阵,利用深度搜索算法,求出最短路径。从最后的运行结果,可以直观的看出搜索的过程

深度搜索算法查找最短路径深度搜索算法查找最短路径

代码实现如下:


#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;

#define M 99999999

const int CityNum = 5;
const int cityMap[CityNum][CityNum] =
{
	0,2,M,M,10,
	M,0,3,M,7,
	4,M,0,4,M,
	M,M,M,0,5,
	M,M,3,M,0
};
bool book[CityNum] = { false };
int iMin = M;
vector<int> vecPath;
void ShowPath()
{
	for (size_t i=0; i<vecPath.size(); i++)
	{
		printf("->%d", vecPath[i]+1);
	}
}
void dfs(int iCur, int iDes, int iDis)
{
	vecPath.push_back(iCur);
	if (iDis > iMin)
	{
		ShowPath();
		printf("->More than Min:%d>%d\r\n", iDis, iMin);
		return;
	}
	if (iDes == iCur)
	{
		if (iDis < iMin)
		{
			iMin = iDis;
		}
		ShowPath();
		printf("->MinPath:%d\r\n", iMin);
		return;
	}

	for (int i=0; i<CityNum; i++)
	{
		if (cityMap[iCur][i] != M && !book[i])
		{
			book[i] = true;
			dfs(i, iDes, iDis + cityMap[iCur][i]);
			vecPath.pop_back();
			book[i] = false;
		}
		else
		{
			ShowPath();
			printf("->%dX\r\n", i + 1);
		}

	}

}

int main()
{
	book[0] = true;
	dfs(0, 4, 0);
	printf("Shortest path is %d", iMin);
	
	return 0;
}

运行结果:打印出路径

深度搜索算法查找最短路径

相关文章:

  • 2021-11-06
  • 2021-08-30
  • 2021-08-11
  • 2021-04-04
  • 2021-09-09
  • 2021-08-11
  • 2019-02-16
猜你喜欢
  • 2021-10-07
  • 2021-05-06
  • 2021-10-02
  • 2021-08-08
  • 2021-09-09
相关资源
相似解决方案