1. 程式人生 > >DFS(入門題)

DFS(入門題)

HDU 1241

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



 

這題還是比較好理解的,有著重疊的子問題,呼叫遞迴即可,感覺和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 }