蛇行矩阵解法(java版)

蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。

输入:

本题有多组数据,每组数据由一个正整数N组成。(N不大于100)

输出:

对于每一组数据,输出一个N行的蛇形矩阵。两组输出之间不要额外的空行。矩阵三角中同一行的数字用一个空格分开。行尾不要多余的空格。

方法一:直接按行、列规律

import java.util.Scanner;
public class Main {
//    static long starTime;
//    static long endTime;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
//		starTime = System.currentTimeMillis();
		int m ;//用来输出的元素
		int count = 0;//用来作行加法
		int t = 1;//记录上一行的首个元素
		while(n!=0) {//控制行
			m = t;
			m += count;
			t = m;
			for(int i=1;i<=n;i++) {//控制列
				System.out.print(m);
				m=m+i+1+count;//进行列加法
				if(i!=n) {
					System.out.print(" ");
				}else {
					System.out.println();
				}
			}
			n--;count++;
		}
//		endTime = System.currentTimeMillis();
//		System.out.println("runtime:"+(endTime-starTime));
	}
}

方法二:发现蛇形矩阵元素的分布规律

import java.util.Scanner;
public class Test {
//	static long starTime;
//	static long endTime;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
//		starTime = System.currentTimeMillis();
		int[][] arr = new int[n][n];
		int count = 1;
		for(int x=0; x<n; x++) {//根据蛇形矩阵元素分布规律直接先把元素存进数组中
			for(int y=0; y<=x; y++) {
				arr[x-y][y] = count++;
			}  
		}
		for(int i=0;i<n;i++) {
			for(int j=0;j<n-i;j++) {
				System.out.print(arr[i][j]);
				if(j!=n-i-1) {
					System.out.print(" ");
				}else {
					System.out.println();
				}
			}
		}
//		endTime = System.currentTimeMillis();
//		System.out.println("runtime:"+(endTime-starTime));
	}
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识汲取者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值