1. 程式人生 > >【leetcode】59.(Medium) Spiral Matrix II

【leetcode】59.(Medium) Spiral Matrix II

解題思路:
就是一圈一圈的加數字,分別上、右、下、左的加

提交程式碼:

class Solution {
	public int[][] generateMatrix(int n) {
		int[][] ans = new int[n][n];

		int cntUp = (int) Math.ceil(n / 2.0);
		int cntLeft = cntUp, cntRight = n / 2, cntBottom = n / 2;
		int pUp = 0, pRight = 0, pBottom = 0, pLeft = 0;
		int num = 1;

		while
(pUp < cntUp) { // add up for (int j = pUp; j < n - pUp; j++) ans[pUp][j] = num++; // add right if (pRight < cntRight) { for (int j = pRight + 1; j < n - 1 - pRight; j++) ans[j][n-1-pRight] = num++; } // add bottom if (pBottom < cntBottom) { for (int
j = n - 1 - pBottom; j >= pBottom; j--) ans[n - 1 - pBottom][j] = num++; } // add left if (pLeft < cntLeft) { for (int j = n - 2 - pLeft; j >= 1 + pLeft; j--) ans[j][pLeft] = num++; } pUp++;pBottom++;pRight++;pLeft++; } return ans; } }

執行結果:
在這裡插入圖片描述