打印具有给定中心的矩形图案
给定3 个正整数c1、c2和n,其中n是二维方阵的大小。任务是打印填充有矩形图案的矩阵,其中心坐标为c1,c2 ,使得0 <= c1,c2 < n。
例子:
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
方法:这个问题可以通过使用两个嵌套循环来解决。请按照以下步骤解决此问题:
- 使用变量 i 在范围 [0, N-1] 中迭代并执行以下步骤:
- 使用变量 j 在范围 [0, N-1] 中迭代并执行以下步骤:
- 打印 abs(c1 – i) 和 abs(c2 – j) 的最大值。
- 打印新行。
- 使用变量 j 在范围 [0, N-1] 中迭代并执行以下步骤:
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print the matrix filled
// with rectangle pattern having center
// coordinates are c1, c2
void printRectPattern(int c1, int c2, int n)
{
// Iterate in the range[0, n-1]
for (int i = 0; i < n; i++) {
// Iterate in the range[0, n-1]
for (int j = 0; j < n; j++) {
cout << (max(abs(c1 - i), abs(c2 - j))) << " ";
}
cout << endl;
}
}
// Driver Code
int main()
{
// Given Input
int c1 = 2;
int c2 = 2;
int n = 5;
// Function Call
printRectPattern(c1, c2, n);
// This code is contributed by Potta Lokesh
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to print the matrix filled
// with rectangle pattern having center
// coordinates are c1, c2
static void printRectPattern(int c1, int c2, int n)
{
// Iterate in the range[0, n-1]
for(int i = 0; i < n; i++)
{
// Iterate in the range[0, n-1]
for(int j = 0; j < n; j++)
{
System.out.print((Math.max(Math.abs(c1 - i),
Math.abs(c2 - j))) + " ");
}
System.out.println();
}
}
// Driver code
public static void main(String[] args)
{
// Given Input
int c1 = 2;
int c2 = 2;
int n = 5;
// Function Call
printRectPattern(c1, c2, n);
}
}
// This code is contributed by sanjoy_62
Python3
# Python3 program for the above approach
# Function to print the matrix filled
# with rectangle pattern having center
# coordinates are c1, c2
def printRectPattern(c1, c2, n):
# Iterate in the range[0, n-1]
for i in range(n):
# Iterate in the range[0, n-1]
for j in range(n):
print(max(abs(c1 - i), abs(c2 - j)), end = " ")
print("")
# Driver Code
# Given Input
c1 = 2
c2 = 2
n = 5
# Function Call
printRectPattern(c1, c2, n)
C#
// C# program for the above approach
using System;
class GFG{
// Function to print the matrix filled
// with rectangle pattern having center
// coordinates are c1, c2
static void printRectPattern(int c1, int c2, int n)
{
// Iterate in the range[0, n-1]
for(int i = 0; i < n; i++)
{
// Iterate in the range[0, n-1]
for(int j = 0; j < n; j++)
{
Console.Write((Math.Max(Math.Abs(c1 - i),
Math.Abs(c2 - j))) + " ");
}
Console.WriteLine();
}
}
// Driver Code
public static void Main(String[] args)
{
// Given Input
int c1 = 2;
int c2 = 2;
int n = 5;
// Function Call
printRectPattern(c1, c2, n);
}
}
// This code is contributed by target_2
Javascript
输出:
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
时间复杂度: O(N ^2)
辅助空间: O(1)