题解 | 递归解法 #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int line = Integer.parseInt(in.nextLine()); int[][] ints = new int[line][line]; // ints[0][0] = 1; int[][] row = row(ints, 1, 0, 0, line); for (int x = 0; x < line; x++) { for (int y = 0; y < line; y++) { int num = row[x][y]; if (num != 0) { System.out.print(num + " "); } } System.out.println(); } } public static int[][] row(int[][] ints, int num, int x, int y, int lines) { // x轴大于一维数组长度时终止递归 if (x >= lines) { return ints; } ints[x][y] = num; if (x == 0) { // x等于0时表示表示已经移动到最顶端 // 移动路线从(x,0)移动到(0,y) // 将x轴向下移动一行,y轴归零,继续递归 x = y + 1; y = 0; } else { // 每次递归时从左下角向右上角移动 x--; y++; } row(ints, ++num, x, y, lines); return ints; } }