Enter a n*n black and white image (1 for black, 0 for White), and the task is to count the number of eight connected blocks. If two black squares have a common edge or a public vertex, they are said to belong to the same eight-connected block.
Sample input:
6
100100
001010
000000
110000
111000
010100
Sample output:
3
Iterate through each black lattice, searching around the center of the black lattice and stopping the search if it is visited (i.e. vis[i][j]=1).
#include <stdio.h> #include <memory.h> #include <string.h> int mat[100][100],vis[100][100];
Char s[100]; void Dfs (int i,int j) {if (vis[i][j]| |
mat[i][j]==0) return;
Vis[i][j]=1;
DFS (I-1,J-1);d FS (I-1,J);d FS (i-1,j+1); DFS (I,J-1);
DFS (I,J+1); DFS (I+1,J-1);
DFS (I+1,J);d FS (i+1,j+1);
} int main (void) {///Freopen ("Black and white image. txt", "R", stdin);
int i,j,n,count;
while (scanf ("%d", &n)!=eof) {memset (mat,0,sizeof (MAT));
memset (vis,0,sizeof (VIS));
count=0;
for (i=1;i<=n;i++) {scanf ("%s", s);
for (j=1;j<=n;j++) {mat[i][j]=s[j-1]-' 0 '; }} for (i=1;i<=n;i++) {for (j=1;j<=n;j++) {if (mat[i
][j]&&vis[i][j]==0) {count++;
DFS (I,J);
}}} printf ("%d\n", count); } return 0;
}