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 ]
]

[分析]
实现2参考 https://leetcode.com/discuss/14079/my-super-simple-solution-can-used-for-both-spiral-matrix-and,代码更简洁。

public class Solution {
    // Method 1
    public int[][] generateMatrix1(int n) {
        if (n < 0) return null;
        int[][] board = new int[n][n];
        int rowStart = 0, colStart = 0;
        int radius = n;
        int num = 1;
        while (radius > 0) {
            int i = rowStart, j = colStart;
            // move right
            int upRight = colStart + radius;
            while (j < upRight) {
                board[i][j++] = num++;
            }
            j--;
            if (radius == 1) break;
            // move down
            i++;
            int downRight = rowStart + radius;
            while (i < downRight) {
                board[i++][j] = num++;
            }
            i--;
            // move left
            j--;
            while (j >= colStart) {
                board[i][j--] = num;
                num++;
            }
            j++;
            // move up
            --i;
            while (i > rowStart) {
                board[i--][j] = num;
                num++;
            }
            // update info to start next spiral
            rowStart++; colStart++;
            radius -= 2;
        }
        return board;
    }
    // Method 2
    public int[][] generateMatrix(int n) {
        if (n < 0) return null;
        int[][] matrix = new int[n][n];
        int rowStart = 0, rowEnd = n - 1;
        int colStart = 0, colEnd = n - 1;
        int num = 1;
        while (rowStart <= rowEnd) {
            for (int j = colStart; j <= colEnd; j++) {//move right
                matrix[rowStart][j] = num++;
            }
            rowStart++;
            for (int i = rowStart; i <= rowEnd; i++) {//move down
                matrix[i][colEnd] = num++;
            }
            colEnd--;
            if (rowEnd >= rowStart) {
                for (int j = colEnd; j >= colStart; j--) {//move left
                    matrix[rowEnd][j] = num++;
                }
                rowEnd--;
            }
            if (colEnd >= colStart) {
                for (int i = rowEnd; i >= rowStart; i--) {//move up
                    matrix[i][colStart] = num++;                    
                }
                colStart++;
            }
        }
        return matrix;
    }
}

你可能感兴趣的:(Leetcode - Spiral Matrix II)