java逆时针螺旋输出矩阵

来源:互联网 发布:剩余windows重置计数2 编辑:程序博客网 时间:2024/06/05 16:44
import java.util.Scanner;
/**
 *@author Sun
 * @since
 * @version 1.0
 * 
 **/
public class test1 {
public static void main(String args[]) {
//获取传入的值
Scanner sc=new Scanner(System.in);
int nextInt = sc.nextInt();
int[][] arr = gettx(nextInt, nextInt);
//逆时针循环输出值
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
//如果小于10就在前面加0
if (arr[i][j] < 10) {
System.out.print("0"+arr[i][j] + "\t");
} else {
System.out.print(arr[i][j] + "\t");
}
}
System.out.println();
}
}


/** 
* 换行  获取值jInt   jyInt
*@author Sun
* @retuen 无返回
*/
public static int[][] gettx(int jInt, int jyInt) {
int jMax = jInt; 
int yyMax = jyInt;
int arr[][] = new int[yyMax][jMax];
int x = 0, y = 0;
int xMin = 0, yMin = 0;
int size = jMax * yyMax;
boolean flag = true;
for (int i = 0; i < size; i++) {
arr[y][x] = i + 1;
if ((y + 1) < yyMax && flag) {
y++;
} else if ((x + 1) < jMax && flag) {
x++;
} else {
if (y > yMin) {
y--;
} else if (x > (xMin + 1)) {
x--;
} else {
jMax--;
yyMax--;
xMin++;
yMin++;
y++;
flag = true;
}
}
if ((y + 1) == yyMax && (x + 1) == jMax) {
flag = false;
}
}
return arr;
}
}
0 0
原创粉丝点击