题解 | #蛇形矩阵#

蛇形矩阵

https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    /**
    * 蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。
    * 例如,当输入5时,应该输出的三角形为:
    * 1 3 6 10 15
    * 2 5 9 14
    * 4 8 13
    * 7 12
    * 11
    */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int N = in.nextInt();
            // 将蛇形右旋45°,一个等腰△ 元素个数 =(首项+尾项)x项数/2
            int size = (N + 1) * N /2;
            //if N==5 将数值1-15从小到大排序后,观察[i][j]规律
            //i:[0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0]-->[0,10,210,3210,43210]
            //j:[0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4]-->[0,01,012,0123,01234]
            int[] iArray = new int[size];//二维数组,第一列下标
            int[] jArray = new int[size];//二位数组,子序列下标
            int indexI = 0, indexJ = 0;
            int countI = 0, countJ = 0;
            for (int x = 0; x < size; x++) {
                //填充i;
                if (indexI == 0) {//遇0,递增下一轮
                    iArray[x] = indexI;
                    countI++;
                    indexI = countI;
                } else {
                    iArray[x] = indexI;
                    indexI--;
                }
                //填充j
                if (indexJ == countJ) {//遇峰值,归零下一轮
                    jArray[x] = indexJ;
                    countJ++;
                    indexJ = 0;
                } else {
                    jArray[x] = indexJ;
                    indexJ++;
                }
            }
            int[][] arr = new int[N][N];
            for (int x = 0; x < size; x++) {
                arr[iArray[x]][jArray[x]] = x + 1;
            }
            for (int[] ints : arr) {
                for (int i : ints) {
                    if (i == 0) continue;
                    System.out.print(i + " ");
                }
                System.out.println();
            }
        }
    }


}

全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务