首页 > 代码库 > 1562 poj dfs
1562 poj dfs
#include<stdio.h>
char grid[101][101];
int n, m;
int dir[8][2] =
{
{-1, -1}, {-1, 0},
{-1, 1}, { 0, 1},
{ 1, 1}, { 1, 0},
{ 1, -1}, { 0, -1}
};
void dfs(int x, int y)
{
int a, b;
grid[x][y] = ‘*‘;
for(int i = 0; i < 8; i++) {
a = x + dir[i][0];
b = y + dir[i][1];
if(a >= 0 && a < m && b >= 0 && b < n && grid[a][b] == ‘@‘) dfs(a, b);
}
}
int main()
{
while(scanf("%d %d", &m, &n), m) {
int ans = 0;
for(int i = 0; i < m; i++) {
scanf("%s", grid[i]);
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == ‘@‘) {
dfs(i, j);
ans++;
}
}
}
printf("%d\n", ans);
}
return 0;
}