59. Spiral Matrix II

    /*
     * 59. Spiral Matrix II 
     * 12.5 by Mingyang
     * 注意,这里我们说的Matrix就是正方形,不再是长方形了,所以我们会用
     * 更简单的方法,就是直接上下左右分别加1就好了,最后再判断是否有中间那个
     * 不用向I一样在里面判断是否是需要判断while里面只有一行或者一列
     */
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int k = 1;
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        while (left < right && top < bottom) {
            for (int j = left; j < right; j++) {
                res[top][j] = k++;
            }
            for (int i = top; i < bottom; i++) {
                res[i][right] = k++;
            }
            for (int j = right; j > left; j--) {
                res[bottom][j] = k++;
            }
            for (int i = bottom; i > top; i--) {
                res[i][left] = k++;
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        if (n % 2 != 0)
            res[n / 2][n / 2] = k;
        return res;
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5472480.html