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
*

*@*@*
**@**
*@*@* @@****@* ****@
*@@*@
*@**@
@@@*@
@@**@
Sample Output



这题还是比较好理解的,有着重叠的子问题,调用递归即可,感觉和DP有点不同,

DP重叠子问题后会有状态的转移,这个只用递归即可。(个人理解,刚学,比较菜)

 #include<bits/stdc++.h>
using namespace std ; char a[][];
void DFS(int x, int y)
{
a[x][y]=;
int X[]={-,-,,,,,,-};
int Y[]={,,,,,-,-,-};
for(int k=; k<; k++){
int i=x+X[k];
int j=y+Y[k];
if(a[i][j]=='@'){
DFS(i,j);
}
}
}
int main ()
{
int n,m;
while(cin>>n>>m)
{
if(n==&&m==)
break; memset(a, , sizeof(a));
for(int i=; i<n; i++)
for(int j=; j<m; j++)
cin>>a[i][j]; int cnt=;
for(int i=; i<n; i++)
for(int j=; j<m; j++)
if(a[i][j]=='@'){
cnt++;
DFS(i,j);
}
cout<<cnt<<endl;
}
return ;
}
 
上一篇:【转】Eclipse的启动问题【an error has occurred see the log file】


下一篇:获取SHA1和MD5