题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312
#include <cstdio>
#include <iostream>
using namespace std;
char a[22][22];
int total = 0;
void dfs(int x, int y);
int main()
{
int w, h;
while(1)
{
int x=0,y=0;
scanf("%d %d",&w,&h);
if(w==0 && h==0)
break;
for(int i=0; i<h; i++)
{
scanf("%s",&a[i]);
getchar();
}
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
if(a[i][j]=='@')
{
x=i;
y=j;
}
}
}
total = 1;
dfs(x,y);
printf("%d\n",total);
}
return 0;
}
void dfs(int x, int y)
{
a[x][y] = '#';
if(a[x-1][y]=='.')
{
total++;
dfs(x-1,y);
}
if(a[x+1][y]=='.')
{
total++;
dfs(x+1,y);
}
if(a[x][y-1]=='.')
{
total++;
dfs(x,y-1);
}
if(a[x][y+1]=='.')
{
total++;
dfs(x,y+1);
}
return;
}
上下左右移动判断一下是否越界就可以啦~
#include<iostream>
#include<cstring>
#include<sstream>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
char a[30][30];
int total = 0;
int w, h;
void dfs(int x, int y)
{
a[x][y]='#';
total++;
if(a[x-1][y]=='.'&&(x-1)>=0&&(x-1)<h&&y<w&&y>=0)
{
dfs(x-1,y);
}
if(a[x+1][y]=='.'&&(x+1)<h&&(x+1)>=0&&y<w&&y>=0)
{
dfs(x+1,y);
}
if(a[x][y-1]=='.'&&(y-1)>=0&&(y-1)<w&&x<h&&x>=0)
{
dfs(x,y-1);
}
if(a[x][y+1]=='.'&&(y+1)<w&&(y+1)>=0&&x<h&&x>=0)
{
dfs(x,y+1);
}
}
int main()
{
while(1)
{
int x=0,y=0;
scanf("%d %d",&w,&h);
memset(a,0,sizeof(a));
if(w==0 && h==0)
break;
total=0;
for(int i=0; i<h; i++)
{
scanf("%s",&a[i]);
getchar();
}
int flag=0;
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
if(a[i][j]=='@')//i是第几行,j是第几列
{
x=i;
y=j;
dfs(x,y);
flag=1;
break;
}
}
if(flag){//如果找到了就可以停止搜索了
break;
}
}
printf("%d\n",total);
}
return 0;
}