#include <stdio.h>#include<string.h>#defineMAX 1000+10CharMat[max][max], Vis[max][max];voidDfsintXintY//mat[][] Save image, 1 for black; vis[][] Mark whether you have visited this lattice{ if(!mat[x][y] | |Vis[x][y]) { return; } Vis[x][y]=1;//flag This point has been visitedDFS (X-1, Y1); DFS (X-1, y); DFS (X-1, y+1);//recursive access to around 8 pointsDFS (x, y1); DFS (x, y+1); DFS (x+1, Y1); DFS (x+1, y); DFS (x+1, y+1);}intMainvoid) {memset (Mat,0,sizeof(MAT)); memset (Vis,0,sizeof(VIS)); intI, J, n, cnt =0; scanf ("%d", &N); for(i=1; i<=n; i++) { for(j=1; j<=n; J + +) {scanf ("%d", &Mat[i][j]); } } for(i=1; i<=n; i++) { for(j=1; j<=n; J + +) { if(Mat[i][j] &&!vis[i][j])//looking for a black lattice that hasn't been visited.{cnt++; DFS (I, j); }}} printf ("%d\n", CNT); return 0;}
Reference Link: http://www.cnblogs.com/RootJie/archive/2012/02/21/2361327.html
This is an example of a white book, just started to study graph theory. This place uses two two-dimensional arrays, one to record the shape of the graph, and the other to determine whether the current point is visited. That is, mat and Vis.
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 public edges or have public vertices, they are said to belong to the same eight-connected block.
As shown, the number of eight-connected blocks is 3.
That is, the input is:
6
1 0 0 1 0 0
0 0 1 0 1 0
0 0 0 0 0 0
1 1 0 0 0 0
1 1 1 0 0 0
0 1 0 1 0 0
Output
3
Dfs that belongs to the entry level
Black and white images