【Leetcode】Spiral Matrix II

题目链接:https://leetcode.com/problems/spiral-matrix-ii/

题目:

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

思路:

1、由外向内一圈一圈的计算,首先计算有几圈,用dim表示,根据dim控制循环次,复杂的地方在于判断每圈每段的起始位置。这种方法思路简单,实现麻烦。

2、用递归实现,参考 http://fisherlei.blogspot.com/2013/04/leetcode-spiral-matrix-ii-solution.html   看起来也挺费劲的。

算法1:

	public int[][] generateMatrix(int n) {
		int matrix[][] = new int[n][n];
		int dim = n / 2;
		if (n % 2 != 0)
			dim++;
		int s = 1;
		for (int i = 0; i < dim; i++) {
			for (int j = i; j < n - i; j++) {//上
				matrix[i][j] = s;
				s++;
			}
			for (int x = i + 1; x < n - i; x++) {//右
				matrix[x][n - i - 1] = s;
				s++;
			}
			for (int x = n - 2 - i; x >= i; x--) {//下
				matrix[n - 1 - i][x] = s;
				s++;
			}
			for (int x = n - 2 - i; x > i; x--) {//左
				matrix[x][i] = s;
				s++;
			}
		}
		return matrix;
	}




你可能感兴趣的:(【Leetcode】Spiral Matrix II)