解题报告
简单的BFS二维搜索,v数组标记已经走过的点,最后统计点的个数。。。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x,y;
}q[1000];
int n,m;
int xx[]={0,-1,0,1};
int yy[]={1,0,-1,0};
char mmap[100][100];
int v[100][100];
void bfs(int x,int y)
{
node now,next;
queue<node>Q;
now.x=x;
now.y=y;
Q.push(now);
v[x][y]=1;
while(!Q.empty())
{
now=Q.front();
Q.pop();
int i;
for(i=0;i<4;i++)
{
next.x=now.x+xx[i];
next.y=now.y+yy[i];
if(next.x>=0&&next.x<m&&next.y>=0&&next.y<n&&mmap[next.x][next.y]!='#'&&v[next.x][next.y]==0)
{
Q.push(next);
v[next.x][next.y]=1;
}
}
}
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m)&&(n&&m))
{
memset(mmap,0,sizeof(mmap));
memset(v,0,sizeof(v));
for(i=0;i<m;i++)
scanf("%*c%s",mmap[i]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(mmap[i][j]=='@')
break;
}
if(j<n)
break;
}
bfs(i,j);
int c=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(v[i][j]==1)c++;
printf("%d\n",c);
}
return 0;
}
DFS道理一样。。。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n,m;
int dx[]= {0,-1,0,1};
int dy[]= {1,0,-1,0};
char mmap[50][50];
void dfs(int s,int e)
{
mmap[s][e]='&';
for(int i=0; i<4; i++)
{
int x=s+dx[i];
int y=e+dy[i];
if(x>=0&&x<n&&y>=0&&y<m&&mmap[x][y]=='.')
{
dfs(x,y);
}
}
}
int main()
{
int i,j;
while(~scanf("%d%d",&m,&n)&&(n+m))
{
memset(mmap,0,sizeof(mmap));
for(i=0; i<n; i++)
scanf("%s",mmap[i]);
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
if(mmap[i][j]=='@')
{
dfs(i,j);
break;
}
}
int cnt=0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
if(mmap[i][j]=='&')
cnt++;
printf("%d\n",cnt);
}
return 0;
}