Eight even blocks
"title" :
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. If 6-11 means 3 eight blocks.
Analysis
Through the topic requirements, the definition of 8-directional array, the use of search to determine that there are several eight connected blocks, search find, look for the mark, to ensure that the original black lattice will not be re-reviewed, but also to consider the boundary problem, but the following my method does not consider the boundary problem, seriously see below to know the method.
Code
#include <stdio.h> #include <stdlib.h> #include <string.h>int mat[10][10],vis[10][10];void dfs (int x , int y) { if (!mat[x][y]| | Vis[x][y]) //To determine whether to have visited, or the current grid is a white return; moving the image to the middle so that it is circled by a circle of white squares, it is not necessary to consider whether or not to cross the border, because the above statement includes the judgment whether the cross- vis[x][y]=1; Tag traversed dfs (x-1,y-1);d FS (x-1,y);d FS (x-1,y+1) that have visited//8 directions; DFS (X,Y-1);d FS (x,y+1); DFS (X+1,Y-1);d FS (x+1,y);d FS (x+1,y+1);} int main () { int n; scanf ("%d", &n); Char s[15]={0}; memset (Mat,0,sizeof (MAT)); memset (vis,0,sizeof (Vis)); int i,j; for (i=0;i<n;i++) { scanf ("%s", s); for (j=0;j<n;j++) mat[i+1][j+1]=s[j]-' 0 '; Move the image to the center of a square, empty a circle of white lattice } int count=0; for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (!vis[i][j]&&mat[i][j]) //If it is a black lattice and has not been visited { count++; DFS (I,J); } printf ("%d\n", count);}
Have any good ideas about the subject, remember message vomit.
Black and white image —————— eight connected blocks