easy
0 views

Boundary Trees

Calculate the final height of trees after M months where boundary trees grow at double the rate of inner trees

Understand the Problem

Problem Statement

Boundary Trees: Certain trees are planted in R rows and C columns in a rectangular field. The current height of the trees are passed as the input. In a month, each tree normally grows by N inches. But the trees on the edge of the rectangular field can grow double the normal rate as they get more sunlight when compared to other trees.

The program must print the height of the trees after M months.

Constraints

  • R and C (number of rows and columns) are between 1 and 20
  • N (growth rate per month) is between 1 and 100
  • M (number of months) is between 1 and 12
  • Tree heights are positive integers
  • All input values are integers

Examples

Example 1
Input
4 3
5 3 6
9 4 10
7 8 7
8 9 9
1 3
Output
11 9 12
15 7 16
13 11 13
14 15 15
Explanation

For a 4x3 grid with normal growth rate of 1 inch per month for 3 months: - Inner trees (position [1,1]) grow by 1*3 = 3 inches: 4 + 3 = 7 - Boundary trees grow by 2*1*3 = 6 inches - Tree at [0,0]: 5 + 6 = 11 - Tree at [0,1]: 3 + 6 = 9 - Tree at [0,2]: 6 + 6 = 12 And so on for all boundary positions.

Solution

#include <stdio.h>

int main() {
    int r, c;
    scanf("%d %d", &r, &c);
    
    int trees[r][c];
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            scanf("%d", &trees[i][j]);
        }
    }
    
    int n, m;
    scanf("%d %d", &n, &m);
    
    int normalGrowth = n * m;
    int boundaryGrowth = 2 * n * m;
    
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            // Check if tree is on boundary (first/last row or first/last column)
            if (i == 0 || i == r - 1 || j == 0 || j == c - 1) {
                trees[i][j] += boundaryGrowth;
            } else {
                trees[i][j] += normalGrowth;
            }
            printf("%d ", trees[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}
Time:O(R*C) - We visit each tree exactly once
Space:O(R*C) - Space required to store the tree heights matrix
Approach:

The C solution follows these steps:

  1. Read R and C dimensions using scanf
  2. Declare a 2D array trees[r][c] to store current heights
  3. Read all tree heights using nested for loops
  4. Read N (growth rate) and M (months)
  5. Calculate growth amounts: normalGrowth = N*M, boundaryGrowth = 2*N*M
  6. Iterate through each tree position:
    • Check if position is on boundary using condition: first row (i==0), last row (i==r-1), first column (j==0), or last column (j==c-1)
    • If boundary: add boundaryGrowth, else add normalGrowth
  7. Print each tree height followed by space, new line after each row

Visual Explanation

Loading diagram...