Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1241
The question is: given a square, some points are ' @ ', some points are ' * '. In the matrix of a ' @ '-centric 3*3, the other ' @ ' and the ' @ ' belong to the same region.
Find out how many areas there are in a square.
Solution: Dfs Deep search
Traversing each point, if the point can be extended deep, expands to 8 directions, and so on, until the end of recursion.
At the end of the recursion, the number of regions is added one, so the points with "relationship" to the point are marked. Then judge the other extensible points.
The code is as follows:
1#include <cstdio>2#include <iostream>3 using namespacestd;4 5 #defineMAXN 1056 7 intM,n;8 CharMAP[MAXN][MAXN];//describe the square9 intdir[8][2]={{-1,-1},{-1,0},{-1,1},{0,1},{0,-1},{1,1},{1,0},{1,-1}};//Description DirectionTen One voidDfsintXinty) A { -map[x][y]='*';//mark each point as non-expandable (already passed) - the intDx,dy; - for(intI=0;i<8; i++)//extend in 8 directions - { -dx=x+dir[i][0]; +dy=y+dir[i][1]; - if(dx<0|| Dx>=m | | dy<0|| Dy>=n)//determine if the inside of the grid + { A Continue; at } - if(map[dx][dy]=='@')//If the point can be extended, recursion - { - DFS (dx,dy); - } - } in } - to intMain () + { - intsum; the while(cin>>m>>N) * { $Cin.Get();//!!!!!!!!!!!!!!!! Panax Notoginseng if(m==0) Break; - the for(intI=0; i<m;i++) + { A for(intj=0; j<n;j++) the { +cin>>map[i][j];//!!!!!!!!!!!!!!!! - } $Cin.Get();//!!!!!!!!!!!!!!!! $ } - -sum=0; the for(intI=0; i<m;i++)//traverse the entire matrix - {Wuyi for(intj=0; j<n;j++) the { - if(map[i][j]=='@') Wu { - DFS (I,J); Aboutsum++; $ } - } - } -printf"%d\n", sum); A } + return 0; the}
View Code
Featured a simple search problem L