原文:
给定 3 正整数 c1,c2 和 n,其中 n 是任务是打印填充有矩形图案的矩阵,该矩形图案具有中心坐标 c1、c2 ,使得 0 < = c1、c2 < n.
示例:
输入 : c1 = 2,c2 = 2,n = 5 输出: 2 2 2 2 2 2 2 2 1 1 2 2 1 0 1 2 2 1 1 2 2 2 2 2 2 2 2 2 2
输入: c1 = 3,c2 = 4,n = 7 t3】输出:t5】4 3 3 3 3 3 3 3 3 4 3 2 2 2 2 4 3 2 1 1 1 2 4 3 2 1 0 1 2 4 3 2 1 1 2 4 3 2 2 2 2 2 2 4 3 3 3 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
python 3
# 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
java 描述语言
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
时间复杂度: o(n ^2) 辅助空间: o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处