【问题标题】:Filling a 2*n room with two different tiles用两个不同的瓷砖填充一个 2*n 的房间
【发布时间】:2021-05-03 23:23:45
【问题描述】:

我遇到了一个问题,我必须填充一个有 2 行和 n 列的矩形。有两个瓷砖,一个是 1*2 瓷砖,第二个是 L 形瓷砖,较大边的尺寸为 2 单位,较小的边尺寸为 1 单位。

我通过动态编程解决了它,但不确定它是否正常工作。如果不是这个问题的正确自下而上代码是什么。 下面是我的解决方案的函数 sn-p。

对于重复,可以以一种方式填充一列,将第一个图块垂直放置,两个相邻的列可以通过将第一种类型的图块一个接一个地水平放置,以一种方式填充。三个相邻的柱子可以通过两个L形倒置排列2种方式填充,四个相邻的柱子可以通过两个L形瓷砖彼此相对和第一种瓷砖水平放置两种方式填充。

int tileways(int n) //n=no.of columns of the rectangle.
{
    int i;
    int a[n+4];
    a[0]=0;
    a[1]=0;
    a[2]=0;
    a[3]=1;
    for(i=4;i<n+4;i++)
    {
        a[i]=a[i-1]+a[i-2]+2*a[i-3]+2*a[i-4];
    }
    return a[n+3];
}

【问题讨论】:

  • 你没有解释这个重复。我认为可以使用三种右端配置来解决 DP:|、L、Г 或两个 | + 2*L 由于对称性
  • @MBo 已编辑。谢谢。
  • C++ 不允许动态长度数组,只有一些编译器支持它,所以在这里考虑std::vector
  • 在我看来 a[1] = 1, a[2] = 2, a[3]=5 (|||, |=, =|. 两个 LL 案例)跨度>
  • @tadman 谢谢。但我想知道逻辑是否正确。还是我错过了什么?

标签: c++ algorithm data-structures dynamic-programming dsa


【解决方案1】:

使用我第一条评论中的方法。

l[3]配置:

L[3] 配置:

#include <iostream>
using namespace std;

int tileways(int n) //n=no.of columns of the rectangle.
{
    int l[20];//straight border
    int L[20];//extra square
    l[0] = 1; 
    l[1] = 1;
    L[0] = 0;
    L[1] = 1;
    for (int i = 2; i <=n; i++) {

        l[i] = l[i-1] + l[i-2] + 2*L[i-2]; 
        //add | to the last straight, = to the 2nd last straight, 
        //two cases of L to extra

        L[i] = l[i-1] + L[i-1];
        //add L to the last straight, - to the extra 
    }
    return l[n];
}

int main() {
    for (int i = 1; i < 10; i++) 
        std::cout<<i<<" "<< tileways(i)<<std::endl;
    return 0;
}

ideone结果

1 1
2 2
3 5
4 11
5 24
6 53
7 117
8 258
9 569

供参考:OEIS sequencenumber of possible tilings of a 2 X n board, using dominos and L-shaped trominos.

1, 2, 5, 11, 24, 53, 117, 258

【讨论】:

  • L数组究竟代表什么?我无法得到那个。
  • 填充长度为 i 且末端呈锯齿状的配置数(L 形的额外正方形或末端的水平条)
  • L[1] 是 1。为什么 1 列可以被 1 tromino 填满?
  • 第一列被填满,第二列包含一个正方形
  • 直到第 i 列的所有列都被完全填满。如果第 (i+1) 列尚不包含方格,则变量计入 l[],如果它包含一个额外的方格 - - 变量计入 L[]
猜你喜欢
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多