31pts求助
查看原帖
31pts求助
247388
WRuperD楼主2021/4/30 11:04

我太菜了

#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
char a[305][305];
bool flag[305][305];
const int distant[4][2] = {{1,0}, {-1,0}, {0,-1}, {0,1}};
struct dis{
	int x, y;
	int t;
};

queue <dis> q;
int main()
{
	int n, m;
	cin>>n>>m;
	int sx, sy;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			cin>>a[i][j];
			if(a[i][j] == '@'){
				sx = i;
				sy = j;
			}
		}
	}
	q.push({sx, sy, 0});
	while(!q.empty())
	{
		int x = q.front().x, y = q.front().y;
//		cout<<x<<' '<<y<<' '<<q.front().t<<endl;
		flag[x][y] = true;
		if(a[x][y] == '='){
			cout<<q.front().t<<endl;
			q.pop();
//			cout<<1<<endl;
			return 0;
		}
		if(a[x][y] != '.')
		{
			bool flag2 = false;
			bool flag3 = false; 
			for(int i = 1; i <= n; i++)
			{
				for(int j = 1; j <= m; j++)
				{
					if(a[i][j] == a[x][y] and (i != x or j != y))
					{
						if(flag[i][j]){
//							q.pop();
							flag2 = true;
							break;
						}	
						else{
							q.push({i,j,q.front().t});
							q.pop();
							flag2 = true;	
							flag3 = true;
							break;
						}
					}
				}
				if(flag2)	break;
			}
			if(flag2 and flag3)	continue;
		}
		for(int i = 0; i <= 3; i++)
		{
			x += distant[i][0], y += distant[i][1];
			if(x > n or y > m or x < 1 or y < 1){
				x -= distant[i][0],y -= distant[i][1];
				continue;
			}
			if(flag[x][y]){
				x -= distant[i][0],y -= distant[i][1];
				continue;	
			}	
			if(a[x][y] == '#'){
				x -= distant[i][0],y -= distant[i][1];
				continue;
			}	
			q.push({x,y,q.front().t+1});
			x -= distant[i][0],y -= distant[i][1];
		}
//		cout<<x<<' '<<y<<' '<<q.front().t<<endl;
		q.pop();
	}
	return 0;
 } 
2021/4/30 11:04
加载中...