螺旋数组java实现

最近一家公司现场笔试题,实现一个回型数组,由于纸张有限,现场没想出简便的方法。回家baidu,好多帖子的代码都一两百行,笔试根本不现实,思索很久,也受到了一些启发,想出了一个简便方法:
//回型数组
import java.util.Scanner;

public class Interview5 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		annulusArr(N);
	}

	public static void annulusArr(int N) {
		int k = 1;
		int[][] arr = new int[N][N];
		int len = N;
		int i = 0, j = 0;
		// 每一轮数组存入最外围的一周,每次存入N-1个,共四次,第二轮存入里面一周,每次N-3个...
		for (int n = N - 1; n > 0; n -= 2) {
			for (int t = 0; t < n; t++)
				arr[i][j++] = k++;

			for (int t = 0; t < n; t++)
				arr[i++][j] = k++;

			for (int t = 0; t < n; t++)
				arr[i][j--] = k++;

			for (int t = 0; t < n; t++)
				arr[i--][j] = k++;

			i++;
			j++;
		}
		// 如果N为奇数,最中间数为零,需单独赋值
		if (N % 2 == 1)
			arr[N / 2][N / 2] = N * N;
		// 输出数组
		for (int n = 0; n < N; n++) {
			for (int m = 0; m < N; m++) {
				System.out.print(arr[n][m] + " \t");
			}
			System.out.println();
		}

	}

}

你可能感兴趣的:(java)