poj1111 dfs

(L又是一道题意复杂的简单题)给你一个R*C的仅有字符’.’(表空格)和字符’X’(表物体)构成的棋盘,现在在给你一个坐标(从1计数),要你算出这个与这个坐标点相连的所有’X’构成物体的外表面周长.

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=30;
int R,C,sr,sc;
char map[maxn][maxn];
int sum;
int dr[]={-1,1,0,0,-1,1,-1,1};//上下左右,左上,左下,右上,右下
int dc[]={0,0,-1,1,-1,-1,1,1};
int DFS(int r,int c)//返回由(r,c)格组成物品的外周长
{
    if(map[r][c]=='.'||map[r][c]=='Y') return 0; //'Y'表示已探索
    map[r][c]='Y';
        //int sum=0;
    for(int d=0;d<4;d++)
        sum+= map[r+dr[d]][c+dc[d]]=='.'?1:0;
    for(int d=0;d<8;d++)
      DFS(r+dr[d],c+dc[d]);
    return sum;              //错误,忘写返回值了
}

int main()
{
    while(scanf("%d%d%d%d",&R,&C,&sr,&sc)==4&&R)
    {
        sum=0;
        memset(map,'.',sizeof(map));    //注意,memset的这种写法
        for(int i=1;i<=R;i++)
        for(int j=1;j<=C;j++)
            scanf(" %c",&map[i][j]);
        printf("%d\n",DFS(sr,sc));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/84557253