【题解】洛谷P1605迷宫 dfs

题目链接
在这里插入图片描述
在这里插入图片描述


#include <bits/stdc++.h>
using namespace std;
void dfs(int,int);
int pace[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//向右、向下、向左、向上
int a[100][100],book[100][100];
int n,m,t,sx,sy,fx,fy,tx,ty,total=0;
int main(){
	cin>>n>>m>>t>>sx>>sy>>fx>>fy;//读入行、列、障碍总数、起点坐标、终点坐标 
	for(int i=1;i<=n;i++){//读入地图 
		for(int j=1;j<=m;j++){
			a[i][j]=0;
		}
	}
	while(cin>>tx>>ty) a[tx][ty]=1;//读入障碍物 
	book[sx][sy]=1;//标记起点 
	dfs(sx,sy);//开始搜索 
	cout<<total<<endl;//输出方案总数 
	return 0;
} 
void dfs(int x,int y){
	if(x==fx&&y==fy){//判断是否到达终点 
		total++;
		return;
	}
	for(int i=0;i<=3;i++){//枚举4种走法 
		int cx=x+pace[i][0];
		int cy=y+pace[i][1];//计算下一个点的坐标 
		if(cx<1||cx>n||cy<1||cy>m) continue;//判断是否越界 
		if(a[cx][cy]==0&&book[cx][cy]==0){//判断有无障碍物和是否在路径中 
			book[cx][cy]=1;//标记这个点已经走过 
			dfs(cx,cy);//开始尝试下一个点 
			book[cx][cy]=0;//尝试结束,取消这个点的标记 
		}
	}
	return;
}

总结

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/82946186