广搜
代码模板
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN = 1e5+5;
ll n,m;
char a[5500][5500];
ll sx,sy,tx,ty;
ll flag[5500][5500];
ll dx[4]={0,0,1,-1};
ll dy[4]={1,-1,0,0};
ll sp;
struct node
{
ll x;
ll y;
ll ans;
};
void bfs()
{
queue<node> op;
op.push({sx,sy,0});
while(!op.empty())
{
node qwq=op.front();
op.pop();
if(qwq.x==tx&&qwq.y==ty)
{
cout<<qwq.ans;
sp=1;
return;
}
if(flag[qwq.x][qwq.y])
continue;
flag[qwq.x][qwq.y]=1;
for(int i=0;i<4;i++)
{
ll x=qwq.x+dx[i];
ll y=qwq.y+dy[i];
if(x<1||x>n||y<1||y>m)
continue;
if(flag[x][y]==1)
continue;
if(a[x][y]=='#')
continue;
op.push({x,y,qwq.ans+1});
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j]=='m')
{
sx=i;
sy=j;
}
if(a[i][j]=='d')
{
tx=i;
ty=j;
}
}
bfs();
if(!sp)
{
cout<<"No Way!";
}
return 0;
}
BFS例题
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PLL;
#define xx first
#define yy second
const ll N = 55;
ll t,n,m,ans;
char s[N][N];
bool st[N][N],flag[N][N], vis[N][N];
queue<PLL> q;
ll dlx[4]={0,0,1,-1};
ll dly[4]={1,-1,0,0};
ll dhx[8]={1,1,1,0,0,-1,-1,-1};
ll dhy[8]={1,0,-1,1,-1,1,0,-1};
void bfs1(ll x,ll y)
{
q.push({x,y});
st[x][y] = true;
while(!q.empty())
{
auto t = q.front();
q.pop();
for(int i=0;i<4;i++)
{
ll a = t.xx + dlx[i];
ll b = t.yy + dly[i];
if(a<0||a>m+1||b<0||b>n+1) continue;
if(st[a][b]) continue;
if(s[a][b] != '1') continue;
st[a][b] = true;
q.push({a,b});
}
}
}
bool bfs2(ll x,ll y)
{
queue<PLL> p;
memset(vis, 0, sizeof vis);
p.push({x,y});
vis[x][y] = 1;
while(!p.empty())
{
auto tt = p.front();
p.pop();
for(int i=0;i<8;i++)
{
ll aa = tt.xx + dhx[i];
ll bb = tt.yy + dhy[i];
if(aa<1||aa>m||bb<1||bb>n)
{
return true;
}
if(s[aa][bb] == '1') continue;
if(vis[aa][bb]) continue;
vis[aa][bb] = 1;
p.push({aa,bb});
}
}
return false;
}
int main()
{
cin>>t;
while(t--)
{
ans = 0;
memset(st,false ,sizeof st);
memset(flag , false , sizeof flag);
cin>>m>>n;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>s[i][j];
for(int i=0;i<=m+1;i++)
for(int j=0;j<=n+1;j++)
{
if(s[i][j] == '1' && !st[i][j])
{
bool res = false;
bfs1(i,j);
res = bfs2(i,j);
if(res)
{
ans++;
}
}
}
cout<<ans<<"\n";
}
return 0;
}