squares id:201

本文介绍了一个用于游戏开发中计算特定大小正方形数量的算法实现过程,包括使用数组保存指令并进行暴力枚举的方法。通过实例演示如何在给定的二维数组中找出所有可能的正方形,并计算其数量。

A children’s board game consists of a square array of dots that contains lines connecting some of the pairs of adjacent dots. One part of the game requires that the players count the number of squares of certain sizes that are formed by these lines. For example, in the gure shown below, there are 3 squares
| 2 of size 1 and 1 of size 2. (The \size” of a square is the number of lines segments required to form a side.)
这里写图片描述
Your problem is to write a program that automates the process of counting all the possible squares

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

分析:
用两个数组来保存指令,然后对每个点进行暴力枚举。对每一个点就遍历一遍指令集。如果在指令集中有使得以该点作为左上顶点的正方形存在,则计数。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int V[10][10], H[10][10], cnt[10], n, m, kase = 0;
int a, b;
char cmd;

int is_exist(int size, int i, int j) {
    for(int h = j; h < j + size; h++)
        if(H[i][h] == 0 || H[i+size][h] == 0)   return 0;
    for(int v = i; v < i + size; v++)
        if(V[v][j] == 0 || V[v][j+size] == 0)   return 0;
    return 1;
}

int main() {

    while(~scanf("%d%d", &n, &m)) {
        memset(V, 0, sizeof(V));
        memset(H, 0, sizeof(H));
        memset(cnt, 0, sizeof(cnt));

        for(int i = 1; i <= m; i++) {
           cin >> cmd >> a >> b;
            if(cmd == 'H')      H[a][b] = 1;
            else                     V[b][a] = 1;
        }

        int size;
        for(size = 1; size < n; size++)
            for(int i = 1; i <= n - size; i++)
                for(int j = 1; j <= n - size; j++) {
                    if(is_exist(size, i, j))
                        cnt[size]++;
                }

        if(kase)       printf("\n**********************************\n\n");
        printf("Problem #%d\n\n", ++kase);
        int flag = 0;
        for(int i = 1; i < n; i++) {
            if(cnt[i] != 0) {
                flag = 1;
                printf("%d square (s) of size %d\n", cnt[i], i);
            }
        }
        if(flag == 0)   printf("No completed squares can be found.\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值