Print rectangular pattern with given center
Last Updated :
23 Jul, 2021
Given 3 positive integer c1, c2 and n, where n is size of 2-D square matrix. The task is to print the matrix filled with rectangular pattern having center coordinates c1, c2 such that 0 <= c1, c2 < n.
Examples:
Input: c1 = 2, c2 = 2, n = 5
Output:
2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2
Input: c1 = 3, c2 = 4, n = 7
Output:
4 3 3 3 3 3 3
4 3 2 2 2 2 2
4 3 2 1 1 1 2
4 3 2 1 0 1 2
4 3 2 1 1 1 2
4 3 2 2 2 2 2
4 3 3 3 3 3 3
Approach: This problem can be solved by using two nested loops. Follow the steps below to solve this problem:
- Iterate in the range[0, N-1], using a variable i and do the following steps:
- Iterate in the range[0, N-1], using a variable j and do the following steps:
- Print maximum of abs(c1 – i) and abs(c2 – j).
- Print new line.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printRectPattern( int c1, int c2, int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
cout << (max( abs (c1 - i), abs (c2 - j))) << " " ;
}
cout << endl;
}
}
int main()
{
int c1 = 2;
int c2 = 2;
int n = 5;
printRectPattern(c1, c2, n);
return 0;
}
|
Java
import java.io.*;
class GFG{
static void printRectPattern( int c1, int c2, int n)
{
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
System.out.print((Math.max(Math.abs(c1 - i),
Math.abs(c2 - j))) + " " );
}
System.out.println();
}
}
public static void main(String[] args)
{
int c1 = 2 ;
int c2 = 2 ;
int n = 5 ;
printRectPattern(c1, c2, n);
}
}
|
Python3
def printRectPattern(c1, c2, n):
for i in range (n):
for j in range (n):
print ( max ( abs (c1 - i), abs (c2 - j)), end = " " )
print ("")
c1 = 2
c2 = 2
n = 5
printRectPattern(c1, c2, n)
|
C#
using System;
class GFG{
static void printRectPattern( int c1, int c2, int n)
{
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
{
Console.Write((Math.Max(Math.Abs(c1 - i),
Math.Abs(c2 - j))) + " " );
}
Console.WriteLine();
}
}
public static void Main(String[] args)
{
int c1 = 2;
int c2 = 2;
int n = 5;
printRectPattern(c1, c2, n);
}
}
|
Javascript
<script>
function printRectPattern(c1, c2, n) {
for (let i = 0; i < n; i++)
{
for (let j = 0; j < n; j++) {
document.write(Math.max(Math.abs(c1 - i), Math.abs(c2 - j)) + " " );
}
document.write( "<br>" );
}
}
let c1 = 2;
let c2 = 2;
let n = 5;
printRectPattern(c1, c2, n);
</script>
|
Output:
2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2
Time Complexity: O(N ^2)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...