题解 | #蛇形矩阵#
蛇形矩阵
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 n = sc.nextInt();
//横向从1开始,加2,加3,加4,加n
int start1 = 1;
int step1 =2;
//竖向从1开始,加1,加2,加3,加n-1
int start2 = 1;
int step2 = 1;
for(;step2<=n;step2++){
System.out.print(start2+" ");
step1 = step2+1;
start1 = start2;
while(step1<=n){
System.out.print(start1+step1+" ");
start1 = start1+step1;
step1++;
}
start2 = start2+step2;
System.out.println();
}
}
}
模拟二维数组法
数据的走向是斜向右上角,每次从左下角开始,往右上角依次增加,横纵坐标的变化分别为 列号从0开始依次加1,加到n-1 行号从1,2,3...n-1每次减1,减到0
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] array = new int[n][n];
int num = 1,count=1;
//构造二维数组
while (count<= n) {
for (int i = count-1, j = 0; i >=0 && j<count;) {
array[i--][j++] = num;
num++;
}
count++;
}
//遍历二维数组
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
if(array[i][j] > 0){
System.out.print(array[i][j] + " ");
}
}
System.out.println();
}
}
}