跳到正文

题解

某岛求药AC代码

Ice_rnfmabj约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

某岛求药WAAC代码

C++
#include<bits/stdc++.h>
using namespace std;
int qx[1010],qy[1010],qs[1010];
int sx,sy;
int n,m;
char Map[1010][1010];
int ans[1010][1010];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void bfs(){
	int h=0,t=0;
	qx[t]=sx;
	qy[t]=sy;
	qs[t++]=0;
	while(h<t){
		for(int i=0;i<=3;i++){
			int tx=qx[h]+dx[i];
			int ty=qy[h]+dy[i];
			if(Map[tx][ty]=='#' || tx<1 || tx>n || ty<1 || ty>m || qs[h]+1>=ans[tx][ty]){
				continue;
			}
			qx[t]=tx;
			qy[t]=ty;
			qs[t++]=qs[h]+1;
			ans[tx][ty]=qs[h]+1;
		}
		h++;
	}
}
int main(){
	int ex,ey;
	while(1){
		cin>>n>>m;
		if(n==0 && m==0){
			break;
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				ans[i][j]=100000;
				cin>>Map[i][j];
				if(Map[i][j]=='@'){
					sx=i;
					sy=j;
				}
				if(Map[i][j]=='*'){
					ex=i;
					ey=j;
				}
			}
		}
		bfs();
		if(ans[ex][ey]==100000){
			cout<<-1<<endl;
		}
		else{
			cout<<ans[ex][ey]<<endl;
		}
	}
	return 0;
}
原文