深度优先搜索
经过的地方就标记一下,没有就 +1
#include <bits/stdc++.h>
#define MAXN 220
#define ll long long
using namespace std;
//上下左右移动
const int dx[] = {0,0,0,-1,1};
const int dy[] = {0,-1,1,0,0};
ll n,m,ans;
bool visted[1010][1010];//标记是否遍历过
char a[1010][1010];
inline bool check(int x,int y){//各种判断 边界 或者是否访问过
if(x < 1 || x > n || y < 1 || y > m || visted[x][y] || a[x][y] == '#')
return false ;
return true;
}
void dfs(ll x,ll y)//深度优先搜索
{
if(!check(x,y))return ;//停止便历条件:超出边界,之前已经遍历过或不符合要求
visted[x][y] = 1;//经过了就标记
ans++;//步数加1
for(int i = 1; i <= 4; i++){//四个方向
int nx = x + dx[i];
int ny = y + dy[i];
dfs(nx,ny);
}
}
int main(){
cin>>m>>n;
while(n!=0&&m!=0) {
ll x,y;
ans=0;
for(long long i=1;i<=n;i++){
for(long long j=1;j<=m;j++){
cin>>a[i][j];
visted[i][j] = 0;
if(a[i][j]=='@')
x=i,y=j;//初始位置
}
}
dfs(x,y);
cout<<ans<<endl;
cin>>m>>n;
}
return 0;
}