Number Square Border

Number Square Border

Hard C Pattern Printing 45 views
Explanation Complexity

Problem Statement

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Boundary layer numbers. Calculate Distance from edge: min(i, j, n-1-i, n-1-j) + 1

Input Format

An integer n representing the size of the square matrix (n × n).

Output Format

Boundary-layer number pattern.

Example

n = 5
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

Constraints

• n ≥ 1

• Square matrix only

Concept Explanation

Each cell value depends on its minimum distance from the edges of the matrix.

Step-by-Step Explanation

1.Use an outer loop for rows i from 0 to n-1.

2.Use an inner loop for columns j from 0 to n-1.

3.For each position (i, j), calculate distance from all four edges:

• Top → i

• Left → j

• Bottom → n - 1 - i

•Right → n - 1 - j

4.Find the minimum distance:

• minDist = min(i, j, n-1-i, n-1-j)

5.The value to print is:

• minDist + 1

6.Print this value with space formatting.

7.After each row, move to the next line.

Concept Explanation

Each cell value depends on its minimum distance from the edges of the matrix.

Step-by-Step Explanation

1.Use an outer loop for rows i from 0 to n-1.

2.Use an inner loop for columns j from 0 to n-1.

3.For each position (i, j), calculate distance from all four edges:

• Top → i

• Left → j

• Bottom → n - 1 - i

•Right → n - 1 - j

4.Find the minimum distance:

• minDist = min(i, j, n-1-i, n-1-j)

5.The value to print is:

• minDist + 1

6.Print this value with space formatting.

7.After each row, move to the next line.

Input / Output Format

Input Format
An integer n representing the size of the square matrix (n × n).
Output Format
Boundary-layer number pattern.
Constraints
• n ≥ 1

• Square matrix only

Examples

Input:
n = 5
Output:
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1

Example Solution (Public)

C
#include <stdio.h>

int main() {
    int n = 5; // size of the square matrix
    int i, j;

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            int layer = i;
            if (j < layer) layer = j;
            if (n - 1 - i < layer) layer = n - 1 - i;
            if (n - 1 - j < layer) layer = n - 1 - j;
            printf("%d ", layer + 1);
        }
        printf("n");
    }

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    int n = 5; // size of the square matrix
    int i, j;

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            int layer = i;
            if (j < layer) layer = j;
            if (n - 1 - i < layer) layer = n - 1 - i;
            if (n - 1 - j < layer) layer = n - 1 - j;
            printf("%d ", layer + 1);
        }
        printf("n");
    }

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.