返回题解分享
讨论 / 题解分享/ 帖子详情

走迷宫输出路径 - 题解

#include<cstdio>
#include<iostream>
using namespace std;

int posit[16][16];
int flag[16][16];
int end1,end2;
int dy[4]={0,-1,0,1};
int dx[4]={-1,0,1,0};
int n,m; 
int count=0; 

string dfs(int y,int x,string s){
	char tmp[12];
	if(y!=end1||x!=end2) {
		sprintf(tmp,"(%d,%d)->",y,x);
		s+=tmp;
	}
	else{
		sprintf(tmp,"(%d,%d)",y,x);
		cout<<s<<tmp<<endl;
		count++;
		return "";
	}
	
	int newy,newx;	
	
	for(int i=0;i<4;++i){
		newy=y+dy[i];
		newx=x+dx[i];
		if(newy>=1&&newy<=n&&newx>=1&&newx<=m&&posit[newy][newx]!=0&&flag[y][x]!=1){
			flag[y][x]=1;
			dfs(newy,newx,s); 
			flag[y][x]=0;
		}			
	}
	
	return s;
};

int main(){
	cin>>n>>m;
	int be1,be2;
	for(int i=1;i<=n;++i)						
	for(int j=1;j<=m;++j) cin>>posit[i][j];	
	
	cin>>be1>>be2>>end1>>end2;
	dfs(be1,be2,"");
	if(count==0) cout<<-1;
	return 0;
	
}
0 回复 0 转发 0 喜欢 5 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!