迷宫

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

const int MAXN = 100;	//迷宫最大范围
int G[MAXN][MAXN];
int m, n;				//迷宫阶数
int ex, ey;				//终点 

bool DFS(int sx, int sy){
	if(ex==sx && ey==sy)
		return true;
	int deltax[] = {0,0,1,-1};
	int deltay[] = {1,-1,0,0};
	for(int i=0; i<4; i++){
		int newx = sx+deltax[i];
		int newy = sy+deltay[i];
		if(newx>=0 && newx<m && newy>=0 && newy<n && G[newx][newy]==1){
			G[newx][newy] = 2;			//该点已经访问过了 
			//DFS(newx, newy);//错误 
			if(true == DFS(newx, newy))
				return true; 
		}
	}
	return false;
}

int main(){
	int sx, sy; 		//起点 
	cout<<"迷宫阶数:\nm=";
	cin>>m;
	cout<<"n=";
	cin>>n;
	
	cout<<"输入迷宫:\n";
	for(int i=0; i<m; i++)
		for(int j=0; j<n; j++)
			cin>>G[i][j]; 
	

	cout<<"输入起点:\nsx=";
	cin>>sx;
	cout<<"sy=";
	cin>>sy; 
	
	cout<<"输入终点:\nex=";
	cin>>ex;
	cout<<"ey=";
	cin>>ey; 
	
	if(G[sx][sy] == 0)
		cout<<"No"<<endl;
	else
		cout<<DFS(sx,sy)<<endl;

	for(int i=0; i<m; i++){
		for(int j=0; j<n; j++)
			cout<<G[i][j]<<" "; 
		cout<<endl; 
	}
	return 0;
}
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;

struct node{
	int x, y;
	node(int x_, int y_):x(x_),y(y_){};
	node(){};
};

int main(){
	const int MAXN = 100;	//迷宫最大范围
	int G[MAXN][MAXN];
	int m, n;				//迷宫阶数
	node ns;				//起点
	node ne;				//终点
	cout<<"输入迷宫阶数:";
	cin>>m>>n;
	cout<<"输入迷宫:\n";
	for(int i=0; i<m; i++)
		for(int j=0; j<n; j++)
			cin>>G[i][j];
			
	cout<<"输入起点:";
	cin>>ns.x>>ns.y;
	cout<<"输入终点:";
	cin>>ne.x>>ne.y;
	
	if(G[ns.x][ns.y] == 0){
		cout<<0;
		return 0;
	}
	if(ns.x==ne.x && ns.y==ne.y){
		cout<<1;
		return 0;
	}
	
	queue<node> Q;
	Q.push(ns);
	G[ns.x][ns.y] = 2;
	while(!Q.empty()){
		node ntop = Q.front();
		Q.pop();	
		
		int deltax[] = {0,0,1,-1};
		int deltay[] = {1,-1,0,0};
		for(int i=0; i<4; i++){
			int newx = ntop.x+deltax[i];
			int newy = ntop.y+deltay[i];
			if(newx==ne.x && newy==ne.y && G[newx][newy]==1){
				cout<<1<<endl;
				for(int i=0; i<m; i++){
					for(int j=0; j<n; j++)
					cout<<G[i][j]<<" "; 
					cout<<endl; 
				}
				return 0;
			}
			if(newx>=0 && newx<m && newy>=0 && newy<n && G[newx][newy]==1){
				G[newx][newy] = 2;
				Q.push(node(newx,newy));
			}
		}
	}
	cout<<0<<endl;

	return 0;
}
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值