难得不会做,还是从基础的做起吧。
注意本题是起点也算答案的一个。
dfs法:
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 30;
const int INF = 1000000;
char Map[N][N];
int m, n, num;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int x, int y)
{
num ++;
for(int i = 0; i < 4; i++)
{
int dx = x + dir[i][0];
int dy = y + dir[i][1];
if(dx >= 0 && dx < m && dy >= 0 && dy < n && Map[dx][dy] == '.')
{
Map[dx][dy] = '#';
dfs(dx, dy);
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
int x, y;
while(~scanf("%d%d", &n, &m) && m!=0 && n!=0)
{
num = 0;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> Map[i][j];
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
{
if(Map[i][j] == '@')
{
x = i;
y = j;
}
}
dfs(x, y);
printf("%d\n", num);
}
return 0;
}
bfs法:
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int N = 30;
const int INF = 1000000;
char Map[N][N];
int m, n, num;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
struct node
{
int x, y;
};
queue <node> q;
void bfs()
{
while(!q.empty())
{
num ++;
node tmp = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
node tmp2;
tmp2.x = tmp.x + dir[i][0];
tmp2.y = tmp.y + dir[i][1];
if(tmp2.x >= 0 && tmp2.x < m && tmp2.y >= 0 && tmp2.y < n && Map[tmp2.x][tmp2.y] == '.')
{
Map[tmp2.x][tmp2.y] = '#';
q.push(tmp2);
}
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
int x, y;
while(~scanf("%d%d", &n, &m) && m!=0 && n!=0)
{
num = 0;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> Map[i][j];
node tmp;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
{
if(Map[i][j] == '@')
{
tmp.x = i;
tmp.y = j;
}
}
q.push(tmp);
bfs();
printf("%d\n", num);
}
return 0;
}