https://vjudge.net/problem/POJ-1562
一道基础的DFS问题,其中牵扯到了染色的问题。与一般的城堡寻屋子问题不一样的时,屋子之间不是相邻的(存在*)。所以需要先写一个枚举,找到一个屋子就Dfs与之相邻的所有@。
注意初始化和边界问题。
//Oil Deposits
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 110;
char grid[maxn][maxn];
int color[maxn][maxn], colorNum = 0; //染色,0表示未染色,-1表示不为油,1-n表示颜色
int m, n;
int action[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {+1, -1}, {-1,+1}};
void Dfs(int x, int y)
{
color[x][y] = colorNum; //染色
//对于每个可移向的方向
for(int i = 0; i < 8; i++){
int sx = x+action[i][0], sy = y+action[i][1];
if(sx>0 && sx<=m && sy>0 && sy<=n && grid[sx][sy]=='@' && color[sx][sy]==0 && (sx!=x || sy!=y))
Dfs(sx, sy);
}
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF && m!=0){
memset(grid, '*', sizeof(grid)), memset(color, 0, sizeof(color));
colorNum = 0;
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++){
scanf(" %c",&grid[i][j]);
if(grid[i][j]=='*') color[i][j]=-1; //把非油地带标记为-1
}
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++)
if(grid[i][j] == '@' && color[i][j]==0){
colorNum++;
Dfs(i,j);
}
printf("%d\n",colorNum);
}
return 0;
}