4kyu Domino Tiling - 3 x N Board
4kyu Domino Tiling - 3 x N Board
題目背景:
A domino is a rectangular block with 2 units wide and 1 unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
## or ##You have infinitely many dominoes, and you want to fill a board that is N units wide and 3 units high:
<--- N ---> ############### ############### ###############The task is to find the number of ways you can fill the given grid with dominoes.
The Twist
But you quickly realize that the answer is zero for any odd N, because (obviously) you can’t cover odd number of cells with dominoes! So you decide to introduce one unit block (1 unit wide and 1 unit high) to cover the final gap when needed (you don’t need this block when N is even).
The following shows some possible tilings for N = 5. Note that, unlike my previous Kata, the numbers do not represent the colors (they are just for convenience). Also note that the unit block (marked as ‘X’) can be placed anywhere on the board, making the answers for odd numbers way higher than even ones.
11255 1122X 14456 3X267 33447 13356 34467 55667 22X77Since the answer will be very large, please give your answer modulo 12345787.
題目分析:
多米諾 2 * 1 拼圖問題其實是一個很經典的遞歸問題,本道題可以說是常見的多米諾問題中最難的一種,雖然只是遞歸問題,不過題目本身的分析難度仍舊相當大,接下來我將從最簡單的情況起步慢慢地分析:
- 情景一
首先分析最簡單的情況,即N * 2的情況:
<--- N ---> ############### ############### 如圖可以找到遞歸關系,即 An = An-1 + An-2,也就是大名鼎鼎的斐波那契數列,初始化 A0 = A1 = 1,由此便可以輕易地碼出代碼。- 情景二
N只是偶數,高度為3的情況。
關于N只是偶數的情況在Geeksforgeeks有詳細的解答,此處我就直接盜圖orz。從最終的狀態分析,最后一列上呈現的狀況只可能是如下三種狀態:
初始情況是:
A0 = 1, A1 = 0 B0 = 0, B1 = 1據此可以碼出最終的代碼。
- 情景三
N既可能是偶數有可能是奇數,同時高度為3,即本題中的情況:
首先依據情景二中的情況分析,當N為偶數時,從偶數下標開始遞推的話,有: A偶 = A偶 + B奇; B奇 = A偶 + B奇,可以發現對于N為偶數的情況時,遞推關系是沿著A偶 及 B奇的方向遞推的,所以我們此時應該分析的是A奇和B偶的情況:
初始情況是:
A0 = 1, A1 = 2 B0 = 0, B1 = 1AC代碼:
# segment the pics and find the law def countWays(n): A = [0] * (n + 1) B = [0] * (n + 1) A[0] = 1A[1] = 2B[0] = 0B[1] = 1for i in range(2, n + 1): if (i % 2):B[i] = (A[i - 1] + B[i - 2]) % 12345787A[i] = (A[i - 2] + 2 * B[i] + 2 * B[i - 1]) % 12345787else:A[i] = (A[i - 2] + 2 * B[i - 1]) % 12345787B[i] = (A[i - 1] + A[i - 2] + B[i - 1] + B[i - 2]) % 12345787return A[n]def three_by_n(n):return countWays(n)總結
以上是生活随笔為你收集整理的4kyu Domino Tiling - 3 x N Board的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3kyu Path Finder #3:
- 下一篇: 4kyu Sum by Factors