上三角的输出 方阵的主对角线之上称为“上三角”。

package org.bluebridge.topics;

/*上三角的输出
 方阵的主对角线之上称为“上三角”。
 请你设计一个用于填充n阶方阵的上三角区域的程序。
 填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
 例如:当n=3时,输出:
 1 2 3
 6 4
 5
 当n=4时,输出:
 1  2 3 4
 9 10 5
 8  6
 7
 当n=5时,输出:
 1  2   3  4  5
 12 13 14  6
 11 15  7
 10  8
 9*/

import java.util.Scanner;

public class UpTriangleOutput {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		sc.close();

		int[][] triangle = new int[n + 1][n + 1];

		// x,y是坐标,num是打印的数字,count是一共多少个数字
		int x = 1, y = 1, num = 1, count = (n + 1) * n / 2;

		while (count > 0) {

			// 打横的(由左往右)
			while (y <= n) {
				triangle[x][y++] = num++;
				count--;
			}
			x++;
			y -= 2;

			// 打斜线的(右上到左下)
			while (x <= n) {
				triangle[x++][y--] = num++;
				count--;
			}
			x -= 2;
			y++;

			// 打直的(由下往上)
			while (x > y) {
				triangle[x--][y] = num++;
				count--;
			}
			x++;
			y++;
			n -= 2;
		}

		for (int i = 1; i < triangle.length; i++) {
			for (int j = 1; j <= triangle[i].length - i; j++) {
				System.out.print(triangle[i][j] + "\t");
			}
			System.out.println();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值