java逆时针螺旋输出矩阵

本文介绍了一个使用Java实现的逆时针螺旋填充二维数组的方法,并展示了如何通过控制台输入来定制矩阵的大小,最后按逆时针方向打印出矩阵的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值