简单的搜索,注意踩到雷就标记不BFS了,还有遇到数字就直接在答案数组里面更新,否则就对 点(空格)就是BFS就行了
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stdlib.h>
#include <string.h>
using namespace std;
const int maxn=600;
int m,n;
int dirx[8]= {0,0,-1,1,1,-1,1,1},diry[8]= {-1,1,0,0,1-1,-1,1};
struct node
{
int x,y;
};
char mat[maxn][maxn],ans[maxn][maxn];
void Init(int x,int y)
{
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
ans[i][j]='.';
}
bool check(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m)
return true;
return false;
}
void Bfs(int x,int y)
{
queue<node>q;
bool vis[maxn][maxn];
memset(vis,true,sizeof(vis));
node a,b;
a.x=x,a.y=y;
q.push(a);
int fx,fy;
ans[x][y]='0';
vis[a.x][a.y]=false;
while(!q.empty())
{
a=q.front();
q.pop();
for(int i=0; i<8; i++)
{
int fx=dirx[i]+a.x;
int fy=diry[i]+a.y;
if(check(fx,fy))
if(vis[fx][fy])
{
vis[fx][fy]=false;
if(mat[fx][fy]=='.')
{
ans[fx][fy]='0';
b.x=fx,b.y=fy;
q.push(b);
}
else
ans[fx][fy]=mat[fx][fy];
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int T,k,x,y,an;
cin>>T;
while(T--)
{
cin>>n>>m>>k;
Init(n,m);
an=0;
for(int i=0; i<n; i++)
cin>>mat[i];
int flag=0;
for(int j=0; j<k; j++)
{
cin>>x>>y;
x--,y--;
if(mat[x][y]=='*'&&flag==0)
flag=1,an=j+1;
else if(flag==1)
continue;
else
{
if(mat[x][y]!='.')
ans[x][y]=mat[x][y];
else
Bfs(x,y);
}
}
if(flag==0)
for(int i=0; i<n; i++)
{
for(int j=0; j<m-1; j++)
cout<<ans[i][j]<<" ";
cout<<ans[i][m-1]<<endl;
}
else
cout<<"Game over in step "<<an<<endl;
}
return 0;
}
本文介绍了一种结合雷区标记与广度优先搜索(BFS)的算法实现,通过处理二维网格上的雷区和数字区域,实现了有效的路径探索与数字更新。特别地,该算法在遇到雷区时会停止搜索并标记,而遇到数字则直接更新答案数组。
2万+

被折叠的 条评论
为什么被折叠?



