题解 | #蛇形矩阵#
蛇形矩阵
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(); int size = (N + 1) * N / 2;// 将蛇形右旋45°,一个等腰△ 个数 =(首项+尾项)x项数/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] List<Integer> listI = new ArrayList<>(size);//二维数组,第一列下标 List<Integer> listJ = new ArrayList<>(size);//二位数组,子序列下标 int indexI = 0, indexJ = 0; int countI = 0, countJ = 0; for (int i = 0; i < size; i++) { //填充i; if (indexI == 0) {//遇0,递增下一轮 listI.add(indexI); countI++; indexI = countI; } else { listI.add(indexI); indexI--; } //填充j if (indexJ == countJ) {//遇峰值,归零下一轮 listJ.add(indexJ); countJ++; indexJ = 0; } else { listJ.add(indexJ); indexJ++; } } int[][] arr = new int[N][N]; for (int i = 0; i < size; i++) { arr[listI.get(i)][listJ.get(i)] = i + 1; } for (int[] ints : arr) { for (int i : ints) { if (i == 0) continue; System.out.print(i + " "); } System.out.println(); } } } }