救!!
查看原帖
救!!
799373
diva233楼主2024/5/22 22:16

代码:(无输出) 求大佬帮忙,初学bfs,做了2个小时实在不会了

#include <bits/stdc++.h>
using namespace std;
bool mp[1001][1001]={true};
struct node{
	int x,y,ans;
};
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int main(){
	int sx,sy,ex,ey,n,m,ans=0;
	cin >>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			char x;
			cin >>x;
			if(x=='.') mp[i][j]=true;
			else mp[i][j]=false;
		}
	}
	node aim;
	aim.x=sx;
	aim.y=sy;
	aim.ans=ans;
	queue<node>q;
	q.push(aim);
	mp[sx][sy]=false;
	while(!q.empty()){
		node to=q.front();
		q.pop();
		if(to.x==ex&&to.y==ey){
			cout <<to.ans<<endl;
		}
		for(int i=0;i<4;i++){
			int tox=to.x+dir[i][0];
			int toy=to.y+dir[i][1];
			int toans=to.ans++;
			if(tox>=1&&toy>=1&&tox<=n&&toy<=m&&mp[tox][toy]==true){
				to.x=tox;
				to.y=toy;
				to.ans=toans;
				mp[to.x][to.y]=false;
				q.push(to);
			}
		}
	}
	return 0;
}
2024/5/22 22:16
加载中...