【问题标题】:Minimal number of cuts of rectangle in squares正方形中矩形的最小切割数
【发布时间】:2020-05-28 23:33:29
【问题描述】:

任务是在正方形中找到最小数量的矩形切割。我为此编写了一个递归函数,但重点是使用动态编程来编写它。我在纸上写了矩阵,但仍然觉得很难写代码。这里 a 和 b 是矩形的尺寸:

int minimalNumOfCuts(int a, int b)
{
    if (a==b) return 0;
    int result;
    if (a<b)
        result = 1+minimalNumOfCuts(b-a,a);//found a square with side a, so I add 1 and recurs on 
    else result = 1+minimalNumOfCuts(a-b,b);//found a square with side b
    return result;
}

例如,对于 3x5 矩形,该函数应返回 3,这是获得一个边为 3 的正方形、一个边为 2 的正方形和两个边为 1 的正方形所需的最小切割数。

当我解决子问题(较小的矩形)时,我认为(如果我使用动态编程)矩阵应该是这样的。不需要带零的列和行。

【问题讨论】:

  • 请详细说明问题,并使用有意义的变量名,以便我们理解您的代码
  • 什么是“动态规划”
  • @pm100,从标签Dynamic programming is an algorithmic technique for efficiently solving problems with a recursive structure containing many overlapping subproblems 的描述来看,OP 可能需要一种递归方法,尽管还不太清楚。
  • 标签文本对我来说读起来像 bs,OP 代码是递归的
  • @pm100,哈哈,因为你没有给我加标签,我差点错过了你的精彩评论,那将是一种耻辱。我不得不同意你的评价。

标签: c dynamic-programming


【解决方案1】:

您使用欧几里得算法遍历矩形,这就是您正在尝试的那种,并计算削减,递归函数有一些可能实现这一点,这是一个可能的实现传递一个计数器指针作为要在内部递归中更改的函数的参数:

Live demo

#include <stdio.h>
#include <stdlib.h>

void minimalNumOfCuts(int side1, int side2, int *count);

int main() {
    int side1 = 3, side2 = 5, count = 0;

    minimalNumOfCuts(side1, side2, &count);
    printf("Height %d Length %d - %d cuts\n", side1, side2, count);

    return EXIT_SUCCESS;
}

void minimalNumOfCuts(int side1, int side2, int *count) {

    if (side1 == side2) {
        return;
    }

    if (side1 > side2) {
        side1 -= side2;
    }
    else {
        side2 -= side1;
    }
    (*count)++;
    minimalNumOfCuts(side1, side2, count); //recursive call
}

输出:

Height 3 Length 5 - 3 cuts

编辑:

对于您的表格,只需循环显示这些值:

此示例使用相同的递归函数计算高度范围为 1 到 5、长度范围为 1 到 4 的矩形的切割数。

Live demo

#define MAX_HEIGHT 5
#define MAX_LENGHT 4

int main() {

    int count = 0;

    for (int i = 1; i < MAX_HEIGHT + 1; i++) {
        for (int j = 1; j < MAX_LENGHT + 1; j++) {   
            minimalNumOfCuts(i, j, &count);
            printf("Height %d Length %d - %d cuts\n", i, j, count);
            count = 0;
        }
    }
    return EXIT_SUCCESS;
}

输出:

Height 1 Length 1 - 0 cuts
Height 1 Length 2 - 1 cuts
Height 1 Length 3 - 2 cuts
Height 1 Length 4 - 3 cuts
Height 2 Length 1 - 1 cuts
Height 2 Length 2 - 0 cuts
Height 2 Length 3 - 2 cuts
Height 2 Length 4 - 1 cuts
Height 3 Length 1 - 2 cuts
Height 3 Length 2 - 2 cuts
Height 3 Length 3 - 0 cuts
Height 3 Length 4 - 3 cuts
Height 4 Length 1 - 3 cuts
Height 4 Length 2 - 1 cuts
Height 4 Length 3 - 3 cuts
Height 4 Length 4 - 0 cuts
Height 5 Length 1 - 4 cuts
Height 5 Length 2 - 3 cuts
Height 5 Length 3 - 3 cuts
Height 5 Length 4 - 4 cuts

Here is a nice graphic demonstration,您可以在其中查看结果。

请注意,您的表格中存在一些不精确之处,例如,具有边 3 和边 4 的矩形将只需要 3 次切割。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多