LeetCode 59. Spiral Matrix II (JAVA)(螺旋矩阵2)

59. 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 ]
]

模仿上一道题的discuss解法,很容易做出

LeetCode-54. Spiral Matrix (JAVA)(顺时针打印矩阵)

	public int[][] generateMatrix(int n) {
		int[][] ret = new int[n][n];
		int left = 0;
		int right = n - 1;
		int up = 0;
		int down = n - 1;
		int count = 1;
		while (left <= right && up <= down) {
			// 右
			for (int j = left; j <= right; j++)
				ret[up][j] = count++;
			up++;
			// 下
			for (int j = up; j <= down; j++)
				ret[j][right] = count++;
			right--;
			// 左
			for (int j = right; j >= left; j--)
				ret[down][j] = count++;
			down--;
			// 上
			for (int j = down; j >= up; j--)
				ret[j][left] = count++;
			left++;

		}
		return ret;
	}



你可能感兴趣的:(leetcode)