题目:

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

分析:

螺旋旋转往数组里添加数字即可

代码:

	public int[][] generateMatrix(int n) {
		int[][] matrix = new int[n][n];
		if (n == 0)
			return matrix;

		// 记录当前方向,0,1,2,3表示向右,向下,向左,向上
		int direction = 0;
		// 记录每个方向前进次数.0,1,2,3记录右,下,左,上
		int[] counter = new int[4];

		loop(matrix, direction, counter, 0, 0, 1);
		return matrix;
	}

	private void loop(int[][] matrix, int direction, int[] counter, int i, int j, int count) {
		matrix[i][j] = count;
		// 螺旋完毕
		if (count == matrix.length * matrix[0].length) {
			return;
		}
		// 先检测当前方向,再查看是否需要转向
		switch (direction) {
		// 向右
		case 0:
			// 需要转向了
			if (j + 1 + counter[1] == matrix[0].length) {
				counter[0] += 1;
				direction = 1;
				loop(matrix, direction, counter, i + 1, j, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i, j + 1, count + 1);
			break;
		// 向下
		case 1:
			// 需要转向了
			if (i + 1 + counter[2] == matrix.length) {
				counter[1] += 1;
				direction = 2;
				loop(matrix, direction, counter, i, j - 1, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i + 1, j, count + 1);
			break;
		// 向左
		case 2:
			// 需要转向了
			if (j == counter[3]) {
				counter[2] += 1;
				direction = 3;
				loop(matrix, direction, counter, i - 1, j, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i, j - 1, count + 1);
			break;
		// 向上
		case 3:
			// 需要转向了
			if (i == counter[0]) {
				counter[3] += 1;
				direction = 0;
				loop(matrix, direction, counter, i, j + 1, count + 1);
				return;
			}
			// 不需要转向
			loop(matrix, direction, counter, i - 1, j, count + 1);
			break;
		}
	}

效率:

leetcode:59. 螺旋矩阵 II

总结:

效率还可以,这里因为没转到的直接是0,有优化空间

相关文章: