poj 1111 dfs(求连通块周长)

本文介绍了一种算法,用于计算给定矩阵中与特定起始位置相连的所有元素组成的图形的周长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:先输入一个矩阵,再输入一个起始位置,然后输出与这个X在八个方向能够连起来的所有X组成的图形的周长。

思路:找到这个连通块显然深搜即可。找周长也很简单,只要对每个位置看看其四周是否不为X,如果是,周长加1。程序里将所有位置初始化为‘.'方便判断。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstdlib>
using namespace std;
#define clc(s,t) memset(s,t,sizeof(s))
#define N 25
char s[N][N];
int n,m,a,b,res;
int ori[8][2] = {{-1,0},{0,1},{1,0},{0,-1},{-1,-1},{-1,1},{1,1},{1,-1}};
int check(int x,int y){
    return x>=1&&y>=1&&x<=n&&y<=m;
}
void dfs(int x,int y){
    int i;
    for(i = 0;i<4;i++)
        if(s[x+ori[i][0]][y+ori[i][1]] == '.')
            res++;
    for(i = 0;i<8;i++){
        int xx = x+ori[i][0];
        int yy = y+ori[i][1];
        if(check(xx,yy) && s[xx][yy]=='X'){
            s[xx][yy] = '@';
            dfs(xx,yy);
        }
    }
}
int main(){
    while(scanf("%d %d %d %d",&n,&m,&a,&b) &&(a+b+n+m)){
        int i;
        clc(s, '.');
        res = 0;
        for(i = 1;i<=n;i++){
            scanf("%s",s[i]+1);
            s[i][m+1] = '.';//勿忘,否则那个位置被'\0'覆盖
        }
        if(s[a][b] == 'X'){
            s[a][b] = '@';
            dfs(a,b);
        }
        printf("%d\n",res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值