蛇形矩阵java版
总体来说就是定义四个方向,定义好上下左右的临界值,当撞墙的时候就换方向,并将刚刚走完的路去除。
import java.util.Scanner;
/**
* @deprecate 2020-01-11
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入一行
int n = sc.nextInt();
// 输入一列
int m = sc.nextInt();
// 初始化数组
int[][] w= new int[n][m];
// 定义数组的边界
int top = 0,left = 0,bottom =w.length-1,right = w[0].length-1;
// 规定一个方向
String dir = "right";
// 目标数
int count = 1;
while (left <= right && top <= bottom){
if(dir=="right"){
for(int i = left;i<=right;i++){
w[top][i] = count;
count++;
}
top++;
dir = "down";
}else if(dir=="down"){
for(int i = top;i<=bottom;i++){
w[i][right] = count;
count++;
}
right--;
dir = "left";
}else if(dir=="left"){
for(int i = right;i>=left;i--){
w[bottom][i] = count;
count++;
}
bottom--;
dir = "top";
}else if(dir=="top"){
for(int i = bottom;i>=top;i--){
w[i][left] = count;
count++;
}
left++;
dir = "right";
}
}
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
System.out.printf("%d ",w[i][j]);
}
System.out.println();
}
}
}