Skip to content

Commit

Permalink
Merge pull request #1825 from NK-Works/tiling
Browse files Browse the repository at this point in the history
Tiling Problem DP Added
  • Loading branch information
pankaj-bind authored Nov 9, 2024
2 parents f186c51 + ebb7f4d commit 6b5eaf7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Dynamic Programming/Tiling Problem/README.md
Original file line number Diff line number Diff line change
@@ -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]`.
28 changes: 28 additions & 0 deletions Dynamic Programming/Tiling Problem/program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <stdio.h>

// 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;
}

0 comments on commit 6b5eaf7

Please sign in to comment.