4 切割纸片

4 切割纸片

作者: 赵晓鹏时间限制: 1S章节: 动态规划与贪心

4 切割纸片_第1张图片

---------------------------------输入

6 4
1 1 0 1
0 0 0 1
0 0 0 1
0 0 0 1
0 0 1 1
0 0 1 1

--------------------输出结果

4
 

#include 
#include 
#include 

using namespace std;

int minCut(vector>& paper, int startRow, int endRow, int startCol, int endCol, vector>>>& dp) {
    // 如果已经计算过该区域的最小切割数,直接返回结果
    if (dp[startRow][endRow][startCol][endCol] != -1) {
        return dp[startRow][endRow][startCol][endCol];
    }

    // 检查当前区域是否是全带洞的纸片或完整的纸片
    bool allHoles = true;
    bool allIntact = true;
    for (int i = startRow; i < endRow; i++) {
        for (int j = startCol; j < endCol; j++) {
            if (paper[i][j] == 1) {
                allIntact = false;
            }
            else {
                allHoles = false;
            }
            if (!allHoles && !allIntact) {
                break;
            }
        }
        if (!allHoles && !allIntact) {
            break;
        }
    }

    // 如果是全带洞的纸片或完整的纸片,则返回0
    if (allHoles || allIntact) {
        dp[startRow][endRow][startCol][endCol] = 0;
        return 0;
    }

    int minCuts = INT_MAX;

    // 水平切割
    for (int i = startRow + 1; i < endRow; i++) {
        int cuts = minCut(paper, startRow, i, startCol, endCol, dp) + minCut(paper, i, endRow, startCol, endCol, dp) + 1;
        minCuts = min(minCuts, cuts);
    }

    // 垂直切割
    for (int j = startCol + 1; j < endCol; j++) {
        int cuts = minCut(paper, startRow, endRow, startCol, j, dp) + minCut(paper, startRow, endRow, j, endCol, dp) + 1;
        minCuts = min(minCuts, cuts);
    }

    dp[startRow][endRow][startCol][endCol] = minCuts;
    return minCuts;
}

int main() {
    int m, n;
    cin >> m >> n;

    vector> paper(m, vector(n));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> paper[i][j];
        }
    }

    // 初始化dp数组为-1
    vector>>> dp(m, vector>>(m + 1, vector>(n, vector(n + 1, -1))));

    int minCuts = minCut(paper, 0, m, 0, n, dp);
    cout << minCuts << endl;

    return 0;
}

你可能感兴趣的:(算法分析与设计作业,算法)