[leetCode] 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 ]
]
public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int x0 = 0, x1 = n - 1, y0 = 0, y1 = n - 1;
        int ele = 0;

        while (x0 <= x1 && y0 <= y1) {
            for (int i = y0; i <= y1; i++) {
                res[x0][i] = ++ele;
            }
            for (int i = x0 +1; i <= x1; i++) {
                res[i][y1] = ++ele;
            }
            if (x0 == x1) break;
            for (int i = y1 - 1; i >= y0; i--) {
                res[x1][i] = ++ele;
            }
            if (y0 == y1) break;
            for (int i = x1 - 1; i > x0; i--) {
                res[i][y0] = ++ele;
            }
            x0++; x1--; y0++; y1--;
        }

        return res;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章