HDU 1241 连通块问题(DFS入门题)
Input
The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
Sample Output
0 1 2 2
这题还是比较好理解的,有着重叠的子问题,调用递归即可,感觉和DP有点不同,
DP重叠子问题后会有状态的转移,这个只用递归即可。(个人理解,刚学,比较菜)
1 #include<bits/stdc++.h> 2 using namespace std ; 3 4 char a[105][105]; 5 void DFS(int x, int y) 6 { 7 a[x][y]=0; 8 int X[8]={-1,-1,0,1,1,1,0,-1}; 9 int Y[8]={0,1,1,1,0,-1,-1,-1}; 10 for(int k=0; k<8; k++){ 11 int i=x+X[k]; 12 int j=y+Y[k]; 13 if(a[i][j]=='@'){ 14 DFS(i,j); 15 } 16 } 17 } 18 int main () 19 { 20 int n,m; 21 while(cin>>n>>m) 22 { 23 if(n==0&&m==0) 24 break; 25 26 memset(a, 0, sizeof(a)); 27 for(int i=0; i<n; i++) 28 for(int j=0; j<m; j++) 29 cin>>a[i][j]; 30 31 int cnt=0; 32 for(int i=0; i<n; i++) 33 for(int j=0; j<m; j++) 34 if(a[i][j]=='@'){ 35 cnt++; 36 DFS(i,j); 37 } 38 cout<<cnt<<endl; 39 } 40 return 0; 41 }