dfs#1TLE,#12WA求助!!
  • 板块P2802 回家
  • 楼主shipeiqian
  • 当前回复1
  • 已保存回复1
  • 发布时间2022/8/9 15:22
  • 上次更新2023/10/27 16:17:32
查看原帖
dfs#1TLE,#12WA求助!!
632063
shipeiqian楼主2022/8/9 15:22
#include <bits/stdc++.h>
using namespace std;
int n,m,x,y,a[10][10],ans=1e9;
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
bool vi[10][10],found=false;
bool check(int x,int y){
	if(x<1||y<1||x>n||y>m)return false;
	if(vi[x][y])return false;
	if(a[x][y]==0)return false;
	return true;
}
void dfs(int x,int y,int hp,int cnt){
	if(hp==0)return ;
	if(a[x][y]==3){
		ans=min(ans,cnt);
		found=true;
		return ;
	}
	vi[x][y]=true;
	if(a[x][y]==4)hp=6;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(check(nx,ny)){
			dfs(nx,ny,hp-1,cnt+1);
		}
	}
	vi[x][y]=false;
}
int main(){
	cin >>n >>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin >>a[i][j];
			if(a[i][j]==2)x=i,y=j;
		}
	}
	dfs(x,y,6,0);
	cout <<(found?ans:-1);
    return 0;
}
2022/8/9 15:22
加载中...