POJ - 1979 Red and Black (dfs+染色)
Click to enter the original title
#### personally think that this question really comes down to count consecutive '.' Number, then the '#' blocked.
#### ideas: @ search to determine the starting position, to become @ '#'; and then look for the four directions to find them one by one into a '#'; define global variables to be counted on time, and finally print out the answer. '' emmm because there may be multiple examples so ans have to remember is initialized to 0;
#include <iostream>
using namespace std;
int w,h,ans=0;
char a[21][21];
void dfs(int i, int j){
a[i][j]='#';ans++;
//查找四个方向
if (a[i+1][j]=='.'&&(i+1)<w)dfs(i+1,j);
if (a[i-1][j]=='.'&&(i-1)>=0)dfs(i-1,j);
if (a[i][j+1]=='.'&&(j+1)<h)dfs(i,j+1);
if (a[i][j-1]=='.'&&(j-1)>=0)dfs(i,j-1);
return ;
}
int main()
{
while(cin >> h >> w)
{
if (w==0&&h==0) return 0;
for (int i=0;i<w;i++){
for(int j=0;j<h;j++){
cin >> a[i][j];
}
}
for (int i=0;i<w;i++){
for(int j=0;j<h;j++){
if (a[i][j]=='@') dfs(i,j);
}
}
cout<< ans<<endl;
ans=0;
}
}
This algorithm was rather powerful, very powerful recursive, wrote out super happy ha ha ha, emmm after all, is just learning the day before yesterday, and today there is a beginning point forgotten ,, ashamed.
-2020.02.12