Red and Black
题目
题解
找出所能到达的所有黑色的数量,用DFS和BFS均可。
BFS:
#include <iostream>
#include <queue>
#define judge(x,y) (x>=0&&x<h&&y>=0&&y<w) //宏定义判断坐标是否越界
using namespace std;
//@start: 2020-04-02 22:20:48
char mp[25][25];//地图
int dir[4][2]={1,0,0,1,-1,0,0,-1};//方向数组
int w,h,ans,dx,dy;
struct node
{//bfs需要结点存入queue
int x,y;
};
void bfs(int x,int y)
{
ans=1;
queue<node> q;
node s,t;
s.x=x,s.y=y;
q.push(s);
while(!q.empty())
{
s = q.front();q.pop();
for(int i=0;i<4;i++)
{//扩展上下左右四个点
t.x = s.x + dir[i][0];
t.y = s.y + dir[i][1];
if(mp[t.x][t.y]=='.'&&judge(t.x,t.y)){
//可走且坐标合法
ans++;
mp[t.x][t.y]='#';
q.push(t);
}
}
}
}
int main()
{
while(cin>>w>>h && w && h)
{
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>mp[i][j];
if(mp[i][j]=='@')
dx=i,dy=j;
}
}
ans=0;
bfs(dx,dy);
cout<<ans<<endl;
}
return 0;
}
DFS:
#include <iostream>
#include <cstdio>
#define judge(x,y) (x>=0&&x<h&&y>=0&&y<w)
using namespace std;
//@start: 2020-04-03 08:48:44
char mp[25][25];
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
int w,h,ans,dx,dy;
void dfs(int x,int y)
{
ans++;
mp[x][y]='#';
for(int i=0;i<4;i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(judge(tx,ty) && mp[tx][ty]=='.'){
dfs(tx,ty);
}
}
}
int main()
{
while(cin>>w>>h && w && h)
{
ans=0;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>mp[i][j];
if(mp[i][j]=='@'){
dx=i;dy=j;
}
}
}
dfs(dx,dy);
cout<<ans<<endl;
}
return 0;
}