求助,双向bfs为什么wa#3#8#10?
查看原帖
求助,双向bfs为什么wa#3#8#10?
1183187
sxhy楼主2024/2/29 23:26
#include<bits/stdc++.h>
using namespace std;
const int N = 2000;
const int N1 = 10000000;
typedef long long ll;
ll w,h, res, g[N][N],xq,yq,zb[N][N],bu[N][N];
int dx[] = { -1,0,1,0 }, dy[] = {0,-1,0,1};
struct node{
	int x, y,bu;

};
queue<node> q, q2;

void bfs() {
	while (!q.empty()||!q2.empty())
	{
		if (!q.empty())
		{
			for (int i = 0; i < 4; i++)
			{
				int x1 = q.front().x + dx[i], y1 = q.front().y + dy[i], bu1 = q.front().bu;
				if (x1 >= 1 && x1 <= h && y1 >= 1 && y1 <= w && zb[x1][y1] != 2
					&& g[x1][y1] != 3 && g[x1][y1] != 1)
				{
					if (zb[x1][y1] == 3 && g[x1][y1] == 4) {
						cout << bu[x1][y1] + bu1 + 1;
						return;
					}
					zb[x1][y1] = 2;
					q.push({ x1,y1,bu1 + 1 });
					//printf("q: x1=%d  y1=%d  bu=%d\n", x1, y1, bu1 + 1);

					
						bu[x1][y1] = bu1 + 1;
					

				}

			}
			q.pop();
		}

			//puts("\n分界线-------");
			if (!q2.empty())
			{
				for (int i = 0; i < 4; i++)
				{
					int x1 = q2.front().x + dx[i], y1 = q2.front().y + dy[i], bu1 = q2.front().bu;

					if (x1 >= 1 && x1 <= h && y1 >= 1 && y1 <= w && zb[x1][y1] != 3
						&& g[x1][y1] != 1)
					{
						if (zb[x1][y1] == 2 && g[x1][y1] == 4) {
							cout << bu[x1][y1] + bu1 + 1;
							return;
						}

						zb[x1][y1] = 3;
						q2.push({ x1,y1,bu1 + 1 });
						
							bu[x1][y1] = bu1 + 1;
						
						//printf("q2: x1=%d y1=%d  bu=%d\n", x1, y1, bu1 + 1);
					}

				}
				q2.pop();
			}
		
		
	}


}

int main() {
	cin >> w >> h;
	for(int i=1;i<=h;i++)
		for (int j = 1; j <= w; j++)
		{
			cin >> g[i][j];
			if (g[i][j]==3) {
				q2.push({i,j,0});
				zb[i][j] = 3;
			}
			if (g[i][j] == 2) {
				q.push({i,j,0});
				zb[i][j] = 2;

			}
		}
	bfs();
	



}
2024/2/29 23:26
加载中...