题解 | #蛇形矩阵#
蛇形矩阵
http://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int start = 1; // 每行初始值 int rowAdd = 2; // 每行第一次递增值 int colAdd = 1; // 第一列递增值 int nowNum = 1; // 当前值 int rowAdd2 = 2; // 每行递增值 for (int i = 0; i < num; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < num - i; j++) { sb.append(nowNum).append(" "); nowNum += rowAdd2++; } System.out.println(sb.toString().trim()); start += colAdd; nowNum = start; rowAdd2 = ++rowAdd; colAdd++; } } }