题目很简单,为了明天比赛回顾一下
http://node1.vjmirror.rainng.com/contest/199100#problem/C
bfs做法
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
char a[30][30];
bool vis[30][30];
int n, m;
int bfs(int x, int y)
{
int ans = 1;
queue<pair<int, int> >q;
pair<int, int> h;
h.first = x, h.second = y;
vis[h.first][h.second] = 1;
q.push(h);
while(! q.empty())
{
h = q.front();
//cout<<h.first<<' '<<h.second<<endl;
if(h.first + 1 <= n && a[h.first+1][h.second] == '.'&&!vis[h.first+1][h.second])
{
vis[h.first+1][h.second] = 1;
q.push({h.first+1, h.second});
ans ++;
}
if(h.first - 1 >= 1 && a[h.first-1][h.second] == '.'&&!vis[h.first-1][h.second])
{
vis[h.first-1][h.second] = 1;
q.push({h.first-1, h.second});
ans ++;
}
if(h.second + 1 <= m && a[h.first][h.second+1] == '.'&&!vis[h.first][h.second+1])
{
vis[h.first][h.second+1] = 1;
q.push({h.first, h.second+1});
ans ++;
}
if(h.second - 1 >= 1 && a[h.first][h.second-1] == '.'&&(!vis[h.first][h.second-1]))
{
vis[h.first][h.second-1] = 1;
q.push({h.first, h.second-1});
ans ++;
}
q.pop();
}
return ans;
}
int main()
{
while(scanf("%d%d",&m,&n) != EOF && (m + n))
{
int x, y;
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n ; i ++)
for(int j = 1; j <= m; j ++)
{
cin>>a[i][j];
if(a[i][j] == '@')
{
x = i;
y = j;
}
}
printf("%d\n",bfs(x, y));
}
return 0;
}
dfs做法
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
char a[30][30];
bool vis[30][30];
int n, m;
int ans;
void dfs(int x, int y)
{
vis[x][y] = 1;
ans ++;
//cout<<x<<' '<<y<<endl;
if(! vis[x+1][y] && x + 1 <= n && a[x+1][y] == '.')
{
dfs(x+1,y);
}
if(! vis[x-1][y] && x - 1 >= 1 && a[x-1][y] == '.')
{
dfs(x-1,y);
}
if(! vis[x][y+1] && y + 1 <= m && a[x][y+1] == '.')
{
dfs(x,y+1);
}
if(! vis[x][y-1] && y - 1 >= 1 && a[x][y-1] == '.')
{
dfs(x,y-1);
}
return ;
}
int main()
{
while(scanf("%d%d",&m,&n) != EOF && (m + n))
{
int x, y;
ans = 0;
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n ; i ++)
for(int j = 1; j <= m; j ++)
{
cin>>a[i][j];
if(a[i][j] == '@')
{
x = i;
y = j;
}
}
dfs(x, y);
printf("%d\n", ans);
}
return 0;
}