84分BFS求解
  • 板块P2802 回家
  • 楼主worstending
  • 当前回复2
  • 已保存回复2
  • 发布时间2024/1/12 19:05
  • 上次更新2024/1/12 21:52:33
查看原帖
84分BFS求解
938807
worstending楼主2024/1/12 19:05
#include<bits/stdc++.h>
using namespace std;
struct re{
	int x,y,z,s;
}; 
queue<re> q;
int n,m;
int a[10][10];
int fx[5]={0,1,-1,0,0};
int fy[5]={0,0,0,1,-1};
bool vis[10][10];
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	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){
				q.push((re){i,j,0,6});
			}
		}	
	}
	while(!q.empty()){
		re x=q.front();
		q.pop();
		for(int i=1;i<=4;i++){
			int tx=x.x+fx[i];
			int ty=x.y+fy[i];
			if(a[tx][ty]==0) continue;
			if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&x.s>1&&!vis[tx][ty]){
				if(a[tx][ty]==1&&x.s>1){
					q.push((re){tx,ty,x.z+1,x.s-1});
					vis[tx][ty]=true;
				}
				if(a[tx][ty]==4&&x.s>1){
					q.push((re){tx,ty,x.z+1,6});
					vis[tx][ty]=true;
				}
				if(a[tx][ty]==3&&x.s>1){
					cout<<x.z+1;
					return 0;		
				}
			}
		}
	}
	cout<<-1;
} 
2024/1/12 19:05
加载中...