[bidirectional BFS template]

Article directory

Original question link:

https://ac.nowcoder.com/acm/contest/549/G
It's a naked two-way BFS problem. I saw a better code. I used to write two BFS's, but this one is written together, and better reflects the idea of layer by layer search
For example, I met it when I was doing a problem. Because I used to debug by output debugging, I didn't know what step to search for when I printed the coordinates. In fact, after searching one layer, I added the next layer
This is a template

The second one will quit as soon as he finds the target, so the return in BFS should be written outside the loop

#include"bits/stdc++.h"
#define out(x) cout<<#x<<"="<<x
#define C(n,m) (m>n?0:(long long)fac[(n)]*invf[(m)]%MOD*invf[(n)-(m)]%MOD)
using namespace std;
typedef long long LL;
const int maxn=1e3+5;
const int MOD=1e9+7;
char G[maxn][maxn];
bool vis[2][maxn][maxn];
int N,M;
struct Node
{
	int x,y;
	Node() {}
	Node(int x,int y):x(x),y(y) {}
};
Node ST1,ST2;//Two starting points
int dx[8]= {1,0,-1,0,1,1,-1,-1};
int dy[8]= {0,1,0,-1,1,-1,1,-1};
queue<Node>que[2];
int BFS(int cmd)
{
	int sz=que[cmd].size();//Essence ~ there is something in the queue that was searched in all directions last time
	while(sz--)
	{
		Node u=que[cmd].front();
		que[cmd].pop();
		for(int i=0; i<4+(cmd==0?4:0); i++) //The first is eight directions
		{
			int xx=u.x+dx[i];
			int yy=u.y+dy[i];
			if(xx<1||xx>N||yy<1||yy>M||G[xx][yy]=='#'||vis[cmd][xx][yy])continue;
			if(vis[cmd^1][xx][yy])return 1;//If you want to exit as soon as you find it here, you can't write it outside the loop as usual 
			vis[cmd][xx][yy]=1;
			que[cmd].push(Node(xx,yy));
		}
	}
	return 0;
}
int solve()
{
	while(!que[0].empty())que[0].pop();
	while(!que[1].empty())que[1].pop();
	que[0].push(ST1);
	que[1].push(ST2);
	memset(vis,0,sizeof vis);
	vis[0][ST1.x][ST1.y]=1;
	vis[1][ST2.x][ST2.y]=1;
	int step=0;
	while(que[0].size()||que[1].size())//As long as one can go, keep going
	{
		step++;
		if(BFS(0))return step;
		if(BFS(1))return step;
		if(BFS(1))return step;//The second one has to take two steps, so we'll do it twice here
	}
	return -1;
}
int main()
{

	while(cin>>N>>M)
	{
		for(int i=1; i<=N; i++)
		{
			for(int j=1; j<=M; j++)
			{
				cin>>G[i][j];
				if(G[i][j]=='C')ST1=Node(i,j);
				else if(G[i][j]=='D')ST2=Node(i,j);
			}
		}
		int ans=solve();
		if(ans==-1)puts("NO");
		else
		{
			puts("YES");
			cout<<ans<<endl;
		}

	}
}

/*
4 5
. C # # . 
# . . # . 
# # . D . 
# . # . . 

*/

Posted by bhavik_thegame on Thu, 28 Nov 2019 08:28:41 -0800