59分玄关求条
查看原帖
59分玄关求条
1128671
lyc_qwq楼主2024/11/27 20:06
#include<bits/stdc++.h>

using namespace std;

inline int read()
{
	int x = 0 , t = 1;
	char ch = getchar();
	while(ch < '0' || ch > '9')
	{
		if(ch == '-')
		{
			t = -1;
		}
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9')
	{
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * t;
}
inline void write(int x)
{
	if(x < 0)
	{
		putchar('-');
	}
	if(x > 9)
	{
		write(x / 10);
	}
	putchar(x % 10 + '0');
}

const int N = 310;
int n , m;
int a1 , b1;
int a2 , b2;
int dx[4] = {0 , 1 , 0 , -1};
int dy[4] = {-1 , 0 , 1 , 0};
char a[N][N];
char s;
int vis[N][N];
struct node
{
	int x;
	int y;
};
queue <node> q;
void bfs(int x , int y)
{
	q.push({x , y});
	a[x][y] = '#';
	vis[x][y] = 0;
	while(q.size())
	{
		node tmp = q.front();
		int tx = tmp.x;
		int ty = tmp.y;
		q.pop();
		for(int i = 0;i < 4; ++ i)
		{
			int ttx = tx + dx[i];
			int tty = ty + dy[i];
			if(ttx >= 1 && ttx <= n && tty >= 1 && tty <= m && a[ttx][tty] != '#')
			{
				if(a[ttx][tty] >= 'A' && a[ttx][tty] <= 'Z')
				{
					vis[ttx][tty] = 1;
					s = a[ttx][tty];
					for(int j = 1;j <= n; ++ j)
					{
						for(int k = 1;k <= m; ++ k)
						{
							if(a[j][k] == s && vis[j][k] == 0)
							{
								ttx = j;
								tty = k;
								q.push({ttx , tty});	
								continue;
							}
						}
					}
				}
				q.push({ttx , tty});
				a[ttx][tty] = '#';
				vis[ttx][tty] = vis[tx][ty] + 1;
			}
		}
	}
}

int main()
{
	n = read() , m = read();
	for(int i = 1;i <= n; ++ i)
	{
		for(int j = 1;j <= m; ++ j)
		{
			cin >> a[i][j];
			if(a[i][j] == '@')
			{
				a1 = i;
				b1 = j;
			}
			if(a[i][j] == '=')
			{
				a2 = i;
				b2 = j;
			}
		}
	}
	bfs(a1 , b1);
	write(vis[a2][b2]);
	return 0;
} 

麻烦大佬们调一下

2024/11/27 20:06
加载中...