Bailian2790 迷宫【DFS】

Bailian2790 迷宫
总时间限制: 3000ms 内存限制: 65536kB
描述
一天Extense在森林里探险的时候不小心走入了一个迷宫,迷宫可以看成是由n * n的格点组成,每个格点只有2种状态,.和#,前者表示可以通行后者表示不能通行。同时当Extense处在某个格点时,他只能移动到东南西北(或者说上下左右)四个方向之一的相邻格点上,Extense想要从点A走到点B,问在不走出迷宫的情况下能不能办到。如果起点或者终点有一个不能通行(为#),则看成无法办到。
输入
第1行是测试数据的组数k,后面跟着k组输入。每组测试数据的第1行是一个正整数n (1 <= n <= 100),表示迷宫的规模是n * n的。接下来是一个n * n的矩阵,矩阵中的元素为.或者#。再接下来一行是4个整数ha, la, hb, lb,描述A处在第ha行, 第la列,B处在第hb行, 第lb列。注意到ha, la, hb, lb全部是从0开始计数的。
输出
k行,每行输出对应一个输入。能办到则输出“YES”,否则输出“NO”。
样例输入
2
3
.##
…#
#…
0 0 2 2
5

###.#
…#…
###…
…#.
0 0 4 0
样例输出
YES
NO

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
char a[110][100];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int k,n,ha, la, hb, lb,ans;
void dfs(int x,int y){
	a[x][y]='#';
	if(x==hb&&y==lb) ans=1;
	if(ans) return;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(nx>=0&&nx<n&&ny>=0&&ny<n){
			if(a[nx][ny]=='.'){
				dfs(nx,ny);
			}
		}
	}
	
}
int main(){
	cin>>k;
	while(k--){
		cin>>n;
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cin>>a[i][j];
			}
		}
		cin>>ha>>la>>hb>>lb;
	ans=0;
	if(a[ha][la]=='#'||a[hb][lb]=='#'){
		ans=0;
	}else{
		dfs(ha,la);
	}
	if(ans) cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	}
}

dfs的另一种写法:

void dfs(int row, int col)
{
    if(row < 0 || row >= n || col < 0 || col >= n)
        return;
    else if(a[row][col] == '#')
        return;
    else if(row == hb && col == lb)
        ans = 1;
    else {
        a[row][col] = '#';
        if(ans == 0) dfs(row + 1, col);
        if(ans == 0) dfs(row - 1, col);
        if(ans == 0) dfs(row, col + 1);
        if(ans == 0) dfs(row, col - 1);
    }
}

更符合个人习惯的:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
using namespace std;
typedef long long ll;
const int MAX=0x3f3f3f3f;
const int N=110;
char a[N][N];
int vis[N][N];
int n,cnt=0;
int max_sum=0,sum=0,ans=0;
int dx[4]={0, -1, 0, 1};
int dy[4]={-1, 0, 1, 0};
int sx,sy,ex,ey;
void dfs(int x,int y){
	if(x==ex&&y==ey){
		ans=1;
		return;
	}
	if(ans) return;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(nx>=0&&nx<n&&ny>=0&&ny<n){
			if(a[nx][ny]=='.'&&vis[nx][ny]==0){
				vis[nx][ny]=1;
				dfs(nx,ny);
			}
		}
	}
}
int main(){
	int k;
	cin>>k;
	while(k--){
		memset(a,0,sizeof(a));
		memset(vis,0,sizeof(vis));
		cin>>n;
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cin>>a[i][j];
			}
		}
		cin>>sx>>sy>>ex>>ey;
		ans=0;
		if(a[sx][sy]=='#'||a[ex][ey]=='#') ans=0;
		else dfs(sx,sy);
		if(ans) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值