首页 > 代码库 > 用java实现螺旋数组

用java实现螺旋数组

接收数组的行数和列数,返回正序和倒序的螺旋数组

package cn.baokx;

public class Test {
	public static void main(String[] args) {
		printArray(getSpiralArray(5,5,false));
		System.out.println("**************");
		printArray(getSpiralArray(5,5,true));
	}
	//打印二维数组
	public static void printArray(int [][] array){
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[0].length; j++) {
	  			if(array[i][j]<10){
	  				System.out.print("0");
	  			}
	  			System.out.print(array[i][j] + " ");
			}
			System.out.println();
		} 
	}
	//返回螺旋数组
	public static int [][] getSpiralArray(int m,int n,boolean reverse){
		//定义一个长度为m*n的数组,并按顺序初始化
		int [] numArray = new int[m*n];
		for(int i = 0 ; i < numArray.length ; i++){
			numArray[i] = (i+1);
		}
		//初始化数组下标
		int foot = reverse?numArray.length-1:0;
		
		//声明螺旋数组
		int[][] array = new int[m][n];
		//计算"层数",以m和n中较小的数为准
		int layer = m<n?m:n;
		layer = (layer%2==1)?(layer / 2 + 1):(layer / 2);
		
		// 从外层到里层循环
		for (int i = 0; i < layer; i++) { 
			//从左到右
			for (int j = i; j < n - i; j++) {
				array[i][j] = numArray[foot];
				foot = reverse?foot-1:foot+1;
				if(foot<0||foot>m*n){
					return array;
				}
			}
			// 从上到下
			for (int j = i + 1;  j < m - i; j++) {
				array[j][n - i - 1] = numArray[foot];
				foot = reverse?foot-1:foot+1;
				if(foot<0||foot>m*n){
					return array;
				}
			}
			// 从右到左
			for (int j = n - i - 2; j >= i; j--) {
				array[m - i - 1][j] = numArray[foot];
				foot = reverse?foot-1:foot+1;
				if(foot<0||foot>m*n){
					return array;
				}
			}
			// 从下到上
			for (int j = m - i - 2; j > i; j--) {
				array[j][i] = numArray[foot];
				foot = reverse?foot-1:foot+1;
				if(foot<0||foot>m*n){
					return array;
				}
			}
		}
		return array;
	}
}


用java实现螺旋数组