diff --git a/Dynamic Programming/Tiling Problem/README.md b/Dynamic Programming/Tiling Problem/README.md new file mode 100644 index 00000000..1533e15c --- /dev/null +++ b/Dynamic Programming/Tiling Problem/README.md @@ -0,0 +1,31 @@ +# Tiling Problem (Cover a 2xN Board with 2x1 Tiles) + +## Problem Description + +The Tiling Problem involves finding the number of ways to cover a \(2 \times N\) board using \(2 \times 1\) tiles. Each tile can either be placed: +- Vertically, which covers a \(1 \times 2\) area on the board. +- Horizontally, which covers a \(2 \times 1\) area on the board. + +Given a positive integer `N`, the goal is to determine the number of ways to completely cover the \(2 \times N\) board using these tiles without gaps or overlaps. + +## Approach + +We can solve this problem using dynamic programming by defining `dp[i]` as the number of ways to tile a \(2 \times i\) board. + +### Steps + +1. **Base Cases**: + - For \( N = 1 \), there is only **1 way** to place a single tile vertically. + - For \( N = 2 \), there are **2 ways**: two vertical tiles or two horizontal tiles. + +2. **Recursive Formula**: + - For each \( i \geq 3 \): + \[ + dp[i] = dp[i - 1] + dp[i - 2] + \] + - This formula is derived from two choices: + - Place a single vertical tile at the end (leaving a \(2 \times (i-1)\) board). + - Place two horizontal tiles at the end (leaving a \(2 \times (i-2)\) board). + +3. **Final Result**: + - The number of ways to tile a \(2 \times N\) board is stored in `dp[N]`. \ No newline at end of file diff --git a/Dynamic Programming/Tiling Problem/program.c b/Dynamic Programming/Tiling Problem/program.c new file mode 100644 index 00000000..8585fadd --- /dev/null +++ b/Dynamic Programming/Tiling Problem/program.c @@ -0,0 +1,28 @@ +#include + +// Function to calculate the number of ways to tile a 2xN board +int tilingProblem(int n) { + if (n == 1) return 1; // Only one way to place a tile vertically + if (n == 2) return 2; // Two ways: two vertical tiles or two horizontal tiles + + int dp[n + 1]; // Array to store the number of ways for each subproblem + dp[1] = 1; + dp[2] = 2; + + for (int i = 3; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; +} + +int main() { + int n; + printf("Enter the length of the board (N): "); + scanf("%d", &n); + + int ways = tilingProblem(n); + printf("Number of ways to tile a 2x%d board is: %d\n", n, ways); + + return 0; +}