题意:一个图中只有红点与黑点,一个人站在一个黑点,红点不能到达,问他能到达的黑点的个数。
思路:bfs。没想到还有这么水的广搜!!!!!!
#include<iostream>
#include<stdio.h>
#include<memory.h>
#include<queue>
using namespace std;
int vis[25][25];
char map[25][25];
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int h,w;
struct node
{
int x;
int y;
};
node s;
int step;
void bfs()
{
step=1;
queue<node> q;
q.push(s);
vis[s.x][s.y]=1;
node temp,t;
while(!q.empty())
{
temp=q.front();
q.pop();
for(int i=0;i<4;i++)
{
if(!vis[temp.x+dirx[i]][temp.y+diry[i]]&&temp.x+dirx[i]>=0&&temp.x+dirx[i]<h&&temp.y+diry[i]>=0&&temp.y+diry[i]<w)
{
vis[temp.x+dirx[i]][temp.y+diry[i]]=1;
t.x=temp.x+dirx[i];
t.y=temp.y+diry[i];
q.push(t);
step++;
}
}
}
cout<<step<<endl;
}
int main()
{
while(cin>>w>>h)
{
if(w==0&&h==0)break;
for(int i=0;i<h;i++)
for(int j=0;j<w;j++)
{
cin>>map[i][j];
if(map[i][j]=='@')
{
s.x=i;
s.y=j;
vis[i][j]=0;
}
else if(map[i][j]=='.')
vis[i][j]=0;
else if(map[i][j]=='#')
vis[i][j]=1;
}
bfs();
}
return 0;
}