代码:
bfs:
#include<cstdio>
#include<queue>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int dir[8][2] = {{-1,0},{-1,1},{0,1},{1,1},
{ 1,0},{1,-1},{0,-1},{-1,-1}};
int g[105][105], vis[105][105];
int m, n;
struct poin {
int x, y;
};
void bfs(int x, int y) {
queue<poin> q;
poin a;
a.x = x;
a.y = y;
q.push(a);
while(!q.empty()) {
int x = q.front().x;
int y = q.front().y;
q.pop();
for(int i=0; i<8; i++) {
int dx = x+dir[i][0];
int dy = y+dir[i][1];
if(dx<m && dx>=0 && dy<n && dy>=0 && g[dx][dy] && !vis[dx][dy]) {
vis[dx][dy] = 1;
poin a;
a.x = dx;
a.y = dy;
q.push(a);
}
}
}
}
int main() {
char temp;
int kase = 1;
while(scanf("%d%d", &m, &n) && (m+n)) {
memset(g, 0, sizeof(g));
for(int i=0; i<m; i++) {
getchar();
for(int j=0; j<n; j++) {
scanf("%c", &temp);
if(temp == '@') g[i][j] = 1;
}
}
memset(vis, 0, sizeof(vis));
int ans = 0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++) {
if(g[i][j] && !vis[i][j]) {
vis[i][j] = 1;
bfs(i, j);
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}
dfs:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int m, n;
int dir[8][2] = {{-1,0},{-1,1},{0,1},{1,1},
{ 1,0},{1,-1},{0,-1},{-1,-1}};
int g[105][105], vis[105][105];
void dfs(int x, int y) {
for(int i=0; i<8; i++) {
int newx = x+dir[i][0];
int newy = y+dir[i][1];
if(newx>=0 && newx<m && newy>=0 && newy<n && g[newx][newy]==1 && !vis[newx][newy]) {
vis[newx][newy] = 1;
dfs(newx, newy);
}
}
}
int main() {
char temp;
int kase = 1;
while(scanf("%d%d", &m, &n) && (m+n)) {
memset(g, 0, sizeof(g));
for(int i=0; i<m; i++) {
getchar();
for(int j=0; j<n; j++) {
scanf("%c", &temp);
if(temp == '@') g[i][j] = 1;
}
}
/* printf("case:%d\n", kase++);
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
if(g[i][j]) printf("%d %d\n", i, j);*/
memset(vis, 0, sizeof(vis));
int ans = 0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++) {
if(g[i][j] && !vis[i][j]){
vis[i][j] = 1;
dfs(i, j);
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}