CODE[VS]1022 覆盖

本文介绍了一个经典的算法题目“1022覆盖”,通过遍历方格并检测是否可以将相邻的陆地格子覆盖来求解最大覆盖数量。使用C语言实现,详细展示了代码结构与逻辑。

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

题目:http://codevs.cn/problem/1022/
思路:遍历所有格子,检测其是否能被覆盖(当前格子为陆地,右方或下方格子为陆地)。
题解:

/* 1022 覆盖 */ 
#include <stdio.h>

#define DEBUG

#define MAXN 101        /* 最大方格数 */ 
#define POOL 2          /* 水塘标记 */ 
#define DRY  1          /* 陆地标记 */ 
#define COV  3          /* 覆盖标记 */ 

int n, m, k;            /* 方格尺寸n*m, 水塘数 */
int grids[MAXN][MAXN];  /* 方格数据 */  
int maxc;               /* 最大覆盖数 */ 

/* 测试 - 打印方格 */
void print_grids(){
    int x, y;
    for(x = 1; x <= n; x++){
        for(y = 1; y <= m; y++){
            printf("%c ", grids[x][y]);
        }
        printf("\n");
    }
    printf("====================%d\n", maxc);
} 

/* 判断格子是否可覆盖*/
int can_cover(int x, int y){
    if((x < 1 || x > n) || (y < 1 || y > m)){
        return 0; 
    } 
    return (DRY == grids[x][y]) ? 1 : 0;
} 
/* 覆盖方格 */
void cover_grids(){
    int xi, yi;
    maxc = 0;
    for(yi = 1; yi <= m; yi++){
        for(xi = 1; xi <= n; xi++){
            if(DRY != grids[xi][yi]){
                continue;
            }
            /* 覆盖当前格子 */
            /* 右方格子为陆地 */
           if(1 == can_cover(xi + 1, yi)){
                grids[xi][yi] = COV;
                grids[xi + 1][yi] = COV;
                maxc++;
            } 
            /* 下面格子为陆地 */
            else if(1 == can_cover(xi, yi + 1)){
                grids[xi][yi] = COV;
                grids[xi][yi + 1] = COV;
                maxc++;
            } 
        }
    }
} 

/* 主函数入口 */ 
int main(int argc, char *argv[]) {
    int x, y;   /* 水塘坐标 */
    int i;      /* 索引值 */ 
#ifdef DEBUG
    FILE *fp;
    if(NULL == (fp = fopen("data.txt", "r"))){
        return 1;
    } 
#endif
    /* 获取方格面积 */ 
#ifdef DEBUG
    fscanf(fp, "%d %d", &n, &m);
#else
    scanf("%d %d", &n, &m);
#endif

    /* 初始化方格 */
    for(x = 1; x <= n; x++){
        for(y = 1; y <= m; y++){
            grids[x][y] = DRY;
        }
    } 
    /* 获取水塘数 */
#ifdef DEBUG
    fscanf(fp, "%d", &k); 
#else
    scanf("%d", &k); 
#endif

    /* 获取水塘数据 */
    for(i = 1; i <= k; i++){
#ifdef DEBUG
        fscanf(fp, "%d %d", &x, &y);
#else
        scanf("%d %d", &x, &y);
#endif 
        grids[x][y] = POOL;
    } 

    /* 遍历每个格子,对其进行覆盖 */ 
    cover_grids();  
    /* 输出结果 */ 
    printf("%d", maxc);
#ifdef DEBUG
    fclose(fp);
#endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值