C++利用DFS算法求迷宫通关最短步骤以及路径

在算出最短的路径的基础上,利用DFS回溯的特性增/删路径,以此来实现对于路径的记录。

PS:最初想通过定义string类型数据来记录路径,但是在回溯删除多余路径时会出现问题(运用函数删除string类型最末尾数据的时候,如果最末尾数据为汉字时会由于数据类型的缘故删除失败出现乱码……求大神的解决方案)

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int a[100][100]={0},v[100][100]={0};
//string b;
char b[100][3];
int n=0;
//string c; 
char c[100][3];
int temp=9999;
int xEnd,yEnd;
int count;
void dfs(int x,int y,int step)
{
	if(x==xEnd && y==yEnd)
	{
		
		if(temp>step)
		{
			//cout << c << endl;
			temp=step;
			for(int i=0;i<n;i++)
			{
				strcpy(c[i],b[i]);
			 } 
			 count=n;
			/*for(int k=0;k<temp;k++)
			{
				strcpy(c[k],b[k]);
			}*/
			//c=b;
			//cout << c << endl;
			return ;
		}
	}
	
	if(a[x-1][y]==1 && v[x-1][y]==1)
	{
		v[x-1][y]=2;
		//b+="上";
		strcpy(b[n++],"上");
		dfs(x-1,y,step+1);
		v[x-1][y]=1;
		strcpy(b[--n],"");
		//b=b.substr(0,b.length()-3);
		//cout<<b<<endl;
		//b.erase(b.end()-1);
	}
	if(a[x+1][y]==1 && v[x+1][y]==1)
	{
		v[x+1][y]=2;
		//b+="下"; 
		strcpy(b[n++],"下");
		dfs(x+1,y,step+1);
		v[x+1][y]=1;
		strcpy(b[--n],"");
		//b=b.substr(0,b.length()-1);
		//cout<<b<<endl;
		//b.erase(b.end()-3);
	}
	if(a[x][y-1]==1 && v[x][y-1]==1)
	{
		v[x][y-1]=2;
		//b+="左"; 
		strcpy(b[n++],"左");
		dfs(x,y-1,step+1);
		v[x][y-1]=1;
		strcpy(b[--n],"");
		//b=b.substr(0,b.length()-1);
		//cout<<b<<endl;
		//b.erase(b.end()-3);
	}
	if(a[x][y+1]==1 && v[x][y+1]==1)
	{
		v[x][y+1]=2;
		//b+="右"; 
		strcpy(b[n++],"右");
		dfs(x,y+1,step+1);
		v[x][y+1]=1;
		strcpy(b[--n],"");
		//b-="右";
		//b=b.substr(0,b.length()-1);
		//cout<<b<<endl;
		//b.erase(b.end()-3);
	}
	
	/*else if((x==1&&y==0)||(x==0&&y==1))
	{
		v[0][0]=1;
	}*/
} 
int main()
{
	int m,n;
	cin >> m >> n ;
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin >> a[i][j] ;
		}
	}
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			v[i][j]=1 ;
		}
	}
	int xStart,yStart;
	cin >> xStart >> yStart ;
	cin >> xEnd >> yEnd ;
	v[xStart][yStart]=2;
	dfs(xStart,yStart,0);
	if(temp==9999)cout<<"没有答案";
	else
	{
		cout << "最短步数" << temp << endl;
		for(int k=0;k<count;k++)
		{
			cout << c[k];
		}
	}
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值