数组--螺旋矩阵II

55 阅读1分钟

给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

代码:

public class SpiralMatrix {
    public static int[][] spiralMatrix(int n) {
        int loop = n / 2;
        int mid = n/2;
        int count = 0;
        int[][] result = new int[n][n];
        int offset = 1;
        int startx = 0;
        int starty = 0;
        while (loop-- > 0) {
            int i = startx;
            int j = starty;
            // 从左到右, 左闭右开
            for (j = starty; j < n - offset; j++) {
                result[startx][j] = count++;
            }
            // 从上到下
            for (i = startx; i < n - offset; i++) {
                result[i][j] = count++;
            }
            // 从右到左
            for (; j > starty; j--) {
                result[i][j] = count++;
            }
            // 从下到上
            for (; i > startx; i--) {
                result[i][j] = count++;
            }
            startx++;
            starty++;
            offset++;
        }

        if (n%2 != 0) {
            result[mid][mid] = count;
        }

        return result;
    }

    public static void main(String[] args) {
        int n = 3;
        System.out.println(Arrays.deepToString(spiralMatrix(3)));
    }
}