bfs 81分 6 10 14点WA求dalao帮忙看一下Orz
查看原帖
bfs 81分 6 10 14点WA求dalao帮忙看一下Orz
671566
virstaring楼主2023/3/25 00:47

bfs 81分 6 10 14点WA求dalao帮忙看一下Orz

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
typedef pair<int, int> PII;

const int N = 310, M = 1e6;

char g[N][N];
int n, m, d[N][N];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
bool vis[N][N];
PII q[M], st, ed;

PII trans(int x, int y)
{
	for(int i = 0; i < n; i ++)
		for(int j = 0; j < m; j ++)
		{
			if(g[i][j] == g[x][y] && (i != x || j != y))
				return {i, j};
		}
}

void bfs()
{
	memset(d, -1, sizeof d);
	int hh = 0, tt = 0;	
	q[0] = st;
	d[st.first][st.second] = 0;
	vis[st.first][st.second] = true;
	
	while(hh <= tt)
	{	
		auto t = q[hh++];
		int x = t.first, y  =t.second;
		
		if(g[x][y] == '=')
		{
		    cout<<d[x][y]<<endl;
		    return;
		}
			
	
		for(int i = 0; i < 4; i ++)
		{
			int nx = x + dx[i], ny = y + dy[i];
			if(nx >= 0 && ny >= 0 && nx < n && ny < m && g[nx][ny] != '#' && !vis[nx][ny])
			{
				if(g[nx][ny] == '.' || g[nx][ny] == '=')
				{
					d[nx][ny] = d[x][y] + 1;
					vis[nx][ny] = true;
					q[++tt] = {nx, ny};

				}
				else
				{
					PII res = trans(nx, ny);
					d[res.first][res.second] =  d[x][y] + 1;
					q[++tt] = res;
				}
			}
		}
	}
	
}

int main()
{
	cin>>n>>m;
	
	for(int i = 0; i < n; i ++)
		for(int j = 0; j < m; j ++)
		{
			cin>>g[i][j];
			if(g[i][j] == '@')
				st = {i, j};
			if(g[i][j] == '=')
				ed = {i, j};
		}
	
	bfs();
	
	return 0;
} 
2023/3/25 00:47
加载中...