思路 – 找规律
输入格式要求:奇数
曼哈顿距离公式:$|x_1 - x_2| + |y_1 - y_2|$
图中蓝色的点到图中的中点的曼哈顿距离为绿色的线,距离为2
;
空格的点任取一个(1, 1)
到中点的距离为3
所以是空格
规律如下:
-
输出
*
的位置的曼哈顿距离 小于等于 方阵n
的一半(n / 2
) -
其他的地方输出空格
C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int cx = n / 2, cy = n / 2;
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
if (abs(i - cx) + abs(j - cy) <= n / 2)
cout << "*";
else
cout << " ";
}
puts("");
}
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sx = n / 2, sy = n / 2;
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < n; j ++)
{
if (Math.abs(sx - i) + Math.abs(sy - j) <= n / 2)
System.out.printf("*");
else
System.out.printf(" ");
}
System.out.printf("\n");
}
}
}