Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tiling Problem DP Added #1825

Merged
merged 2 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading