加农的入侵
描述
输入
* 第一行: 四个由空格隔开的整数: X, Y, Mx, My
* 第2到第Y+1行:每行包含一个由X个字符(".“表示干净区域,而”*"表示障碍物。)构成的字符串,共同描绘了草地的完整地图。
(1≤X,Y≤100)
输出
输出一个整数,表示加农完全占领该区域所需要的天数。
输入样例
4 3 1 1
....
..*.
.**.
输出样例
4
难度
中,BFS
题解
标准广度优先搜索,改编代码武士风度的牛。
注意输入的行列顺序,不然AC不了,这个坑跳了很久没出来
代码
Code by me
#include<bits/stdc++.h>
using namespace std;
struct Point{
int r,c;
};
Point dir[8] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
struct Node{
int col,row;
int count;
};
int Column,Row,Maxcount=0,cnt=0;
queue<Node> Q;
int BFS(char** Board,bool** visited){
while (!Q.empty())
{
Node n = Q.front();
Q.pop();
for(int i=0;i<8;i++){
int col = n.col+dir[i].c;
int row = n.row+dir[i].r;
if(col>=1 && col<=Column && row>=1 && row<=Row && visited[col][row]==false && Board[col][row]!='*'){
Node p;
cnt--;
// cout<<col<<" "<<row<<" "<<n.count+1<<endl;
p.col = col; p.row = row; p.count = n.count+1;
visited[col][row]=true;
Q.push(p);
if(p.count>Maxcount) Maxcount = p.count;
if(cnt==0) return 1;
}
}
}
return 0;
}
int main()
{
int begincol,beginrow;
cin>>Row>>Column;
cin>>beginrow>>begincol;
char **Board = new char*[Column+1];
for(int i = 1 ; i <= Column ; ++i ){
Board[i] = new char [Row+1]();
}
bool **visited = new bool*[Column+1];
for(int i = 1 ; i <= Column ; ++i ){
visited[i] = new bool [Row+1]();
}
memset(visited,false,sizeof(visited));
for(int i=1;i<=Column;i++)
for(int j=1;j<=Row;j++){
cin>>Board[i][j];
if(Board[i][j]=='.')
cnt++;
}
Node n; n.col = Column-begincol+1; n.row = beginrow; n.count = 0;
visited[Column-begincol+1][beginrow] = true;
if(Board[Column-begincol+1][beginrow] == '.') cnt--;
Q.push(n);
int count = BFS(Board,visited);
cout<<Maxcount;
return 0;
}
Code by Andy
#include<bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int i=a;i<b;i++)
const int dx[8] = {1,-1,0,0,1,-1,1,-1};
const int dy[8] = {0,0,1,-1,1,-1,-1,1};
const int N=110;
char s[N][N];
int cnt,n,m;
int visited[N][N],dist[N][N],maxDist;
#define pii pair<int,int>
pii start,qHead;
queue<pii> q;
int check(int x,int y){
return x>=1 && x<=n && y>=1 && y<=m && visited[x][y]==0 && s[x][y]!='*';
}
int bfs(){
q.push(start);
dist[start.first][start.second]=0;
visited[start.first][start.second]=1;
while (q.size())
{
qHead = q.front();
q.pop();
For(i,0,8){
int x=qHead.first+dx[i],y=qHead.second+dy[i];
if(check(x,y)){
cnt--;
visited[x][y]=1;
dist[x][y]=dist[qHead.first][qHead.second]+1;
maxDist=max(maxDist,dist[x][y]);
q.push(make_pair(x,y));
if(cnt==0)
return 1;
}
}
}
return 0;
}
int main(){
scanf("%d%d%d%d\n",&m,&n,&start.second,&start.first);
for(int i=n;i>=1;i--){
for(int j=1;j<=m;j++){
s[i][j]=getchar();
if(s[i][j]=='.')
cnt++;
}
getchar();
}
if(s[start.first][start.second]=='.')
cnt--;
bfs();
cout<<maxDist;
}