Spiral Matrix II(螺旋矩阵 II)

问题

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

Have you met this question in a real interview? Yes
Example
Given n = 3,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

分析

按要求循环添加即可。

代码

public class Solution {
    /*
     * @param n: An integer
     * @return: a square matrix
     */
    public int[][] generateMatrix(int n) {
        // write your code here
        int[][] res = new int[n][n];
        int top = 0;
        int left = 0;
        int right = n - 1;
        int bottom = n - 1;
        while (true) {
            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    if (i == 0) {
                        res[top][i] = 1;
                    } else {
                        res[top][i] = res[top][i - 1] + 1;
                    }
                }
                top++;
            } else {
                break;
            }
            if (right >= left) {
                for (int i = top; i <= bottom; i++) {
                    res[i][right] = res[i - 1][right] + 1;
                }
                right--;
            } else {
                break;
            }
            if (bottom >= top) {
                for (int i = right; i >= left; i--) {
                    res[bottom][i] = res[bottom][i + 1] + 1;
                }
                bottom--;
            } else {
                break;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    res[i][left] = res[i + 1][left] + 1;
                }
                left++;
            } else {
                break;
            }

        }
        return res;
    }
}

你可能感兴趣的:(Spiral Matrix II(螺旋矩阵 II))