Posts PRETTYPRINT (InterviewBit)
Post
Cancel

PRETTYPRINT (InterviewBit)

PROBLEM DESCRIPTION

Print concentric rectangular pattern in a 2d matrix.

Let us show you some examples to clarify what we mean.

Example 1:

Input: A = 4.

Output:

1
2
3
4
5
6
7
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {

    public int[][] prettyPrint(int A) {

        int n = 2*A-1;
        int[][] arr = new int[n][n];

        int current = A;

        int topRow = 0;
        int bottomRow = n-1;
        int leftCol = 0;
        int rightCol = n-1;

        while(topRow <= bottomRow && leftCol <= rightCol){

            for(int c=leftCol; c<=rightCol; c++){
                arr[topRow][c] = current;
            }

            for(int r=topRow; r<=bottomRow; r++){
                arr[r][rightCol] = current;
            }

            for(int c=rightCol; c>=leftCol; c--){
                arr[bottomRow][c] = current;
            }

            for(int r=bottomRow; r>=topRow; r--){
                arr[r][leftCol] = current;
            }

            topRow++;
            bottomRow--;
            leftCol++;
            rightCol--;

            current--;

        }

        return arr;

    }

}
This post is licensed under CC BY 4.0 by the author.