Asterisks – X Inner Layers
Replace characters in the X inner layers of an NxN matrix with asterisks
Understand the Problem
Problem Statement
Given an NxN character matrix and an integer X, replace all characters present in the X inner layers of the matrix with asterisks (*) and print the modified matrix.
A layer is defined as a concentric square boundary within the matrix. The outermost layer is layer 1, the next inner boundary is layer 2, and so on.
Constraints
- 2 ≤ N ≤ 50
- 1 ≤ X ≤ (N+1)/2
- Each character in the matrix is a single printable character
- The matrix is guaranteed to be square (NxN)
Examples
8
b z r p h u w f
c p g b p u a j
n h f a l b i g
j k x n n y k p
k v j f u b l r
z x m a t z x j
s o c u r q d j
x n t v a g y h
2b z r p h u w f
c p g b p u a j
n h * * * * i g
j k * * * * k p
k v * * * * l r
z x * * * * x j
s o c u r q d j
x n t v a g y hWith X=2, the 2 inner layers form a 4x4 region in the center (rows 2-5, columns 2-5). All characters in this region are replaced with asterisks, while the outer 2 layers remain unchanged.
5
H Q G I B
W A U T W
F U O W C
U G R E W
R P K C M
1H Q G I B
W A U T W
F U * W C
U G R E W
R P K C MWith X=1, only the innermost layer (center element) is replaced. In a 5x5 matrix, this is just the element at position [2][2], which becomes '*'.
Solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
char matrix[n][n];
// Read the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf(" %c", &matrix[i][j]);
}
}
int x;
scanf("%d", &x);
// Calculate boundaries for the inner region
int outerLayers = (n / 2) - x + (n % 2);
int start = outerLayers;
int end = n - outerLayers;
// Replace characters in inner region with asterisks
for (int i = start; i < end; i++) {
for (int j = start; j < end; j++) {
matrix[i][j] = '*';
}
}
// Print the modified matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%c", matrix[i][j]);
if (j < n - 1) printf(" ");
}
printf("\n");
}
return 0;
}C Solution Explanation:
- Input Reading: Read matrix size N, then read N×N characters using nested loops and scanf
- Boundary Calculation: Calculate the start and end indices of the inner region that needs modification
- Matrix Modification: Iterate through the inner rectangular region and replace all characters with '*'
- Output: Print the modified matrix with proper spacing between characters
The algorithm efficiently identifies the inner layers by calculating the preserved outer layers and working inward.