LeetCode-Spiral Matrix II

受上一题启发 知道要keep四个变量 分别为四个角的边界 一层一层填充


public class Solution {
    public int[][] generateMatrix(int n) {
        int [][] res = new int [n][n];
        int i = 1;
        int colStart = 0;
        int colEnd = n - 1;
        int rowStart = 0;
        int rowEnd = n - 1;
        while ( i <= n * n ) {
            //go right
            for ( int j = colStart; j <= colEnd; j ++ ){
                res[rowStart][j] = i;
                i ++;
            }
            rowStart ++;
            //go down
            for ( int j = rowStart; j <= rowEnd; j ++ ){
                res[j][colEnd] = i;
                i ++;
            }
            colEnd --;
            // go left;
            for ( int j = colEnd; j >= colStart; j -- ){
                res[rowEnd][j] = i;
                i ++;
            }
            rowEnd --;
            // go up
            for ( int j = rowEnd; j >= rowStart; j -- ){
                res[j][colStart] = i;
                i ++;
            }
            colStart ++;
        }
        return res;
    }
}


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