dfs 深搜
#include <iostream>
using namespace std;
const int N = 30;
int n, m, cnt;
string g[N];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
void dfs(int x, int y)
{
g[x][y] = '#';
cnt ++;
for(int i = 0 ; i < 4; i ++)
{
int tx = x + dx[i], ty = y + dy[i];
if(tx < m && tx >= 0 && ty < n && ty >= 0 && g[tx][ty] == '.')
dfs(tx, ty);
}
return;
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF && n != 0 && m != 0)
{
cnt = 0;
int x, y;
for(int i = 0; i < m; i ++)
cin >> g[i];
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
{
if(g[i][j] == '@')
x = i, y = j;
}
dfs(x, y);
cout << cnt << endl;
}
}
bfs 广搜
#include <iostream>
using namespace std;
struct stu
{
int x;
int y;
}que[2510];
int main()
{
int n, m;
int tx[] = {0, -1, 0, 1}, ty[] = {1, 0, -1, 0};
while( scanf("%d%d", &n, &m) != EOF && n != 0 && m != 0)
{
int p, q, book[25][100] = {0};
char a[25][100];
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
{
cin >> a[i][j];
if(a[i][j] == '@')
p = i, q = j;
}
int x, y, head = 0, tail = 1;
que[0].x = p, que[0].y = q;
while(head < tail)
{
for(int i =0; i < 4; i ++)
{
x = que[head].x + tx[i];
y = que[head].y + ty[i];
if(x < 0 || x >= m || y < 0 || y >= n)
continue;
if(a[x][y] == '.' && book[x][y] == 0)
{
book[x][y] = 1;
que[tail].x = x;
que[tail].y = y;
tail ++;
}
}
head ++;
}
printf("%d\n", tail);
}
}