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

一刷
题解:
跟Spiral Matrix I一样,拥有top, bottom, left, right四个指针以及一个计数器。
Time Complexity - O(n * n), Space Complexity - O(1)。

public class Solution {
    public int[][] generateMatrix(int n) {
        int left=0, right = n-1, top = 0, bottom = n-1;
        int[][] res = new int[n][n];
        if(n==0) return res;
        int total = n*n, count=1;
        while(count<=total){
            for(int i=left; i<=right; i++){
                res[top][i] = count;
                count++;
            }
            top++;
            
            if(count<=total){
                for(int i=top; i<=bottom; i++){
                    res[i][right] = count;
                    count++; 
                }
                right--;
            }
            
            if(count<=total){
                for(int i=right; i>=left; i--){
                    res[bottom][i] = count;
                    count++;
                }
                bottom--;
            }
            
            if(count<=total){
                for(int i=bottom; i>=top; i--){
                    res[i][left] = count;
                    count++; 
                }
                left++;
            }
        }
        return res;
    }
}

你可能感兴趣的:(59. Spiral Matrix II)