# 59. Spiral Matrix II

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MfRvt_MNYbvpmYqlHAY%2F-MfS8et1n0EEdI63DhfS%2Fimage.png?alt=media\&token=a53386e8-ff31-4e9b-9e28-9471e5be9ff1)

time: O(mn)

space: O(mn)

```java
class Solution {
    public int[][] generateMatrix(int n) {
        int res[][] = new int[n][n];
        
        int rowStart = 0;
        int rowEnd = n - 1;
        int colStart = 0;
        int colEnd = n - 1;
        int index = 1;
        
        while (rowStart <= rowEnd && colStart <= colEnd ) {
            for (int i = colStart; i <= colEnd; i++) {
                res[rowStart][i] = index++;
            }
            rowStart++;
            
            for (int i = rowStart; i<= rowEnd; i++) {
                res[i][colEnd] = index++;
            }
            colEnd--;
            
            if (rowStart <= rowEnd) {
                for (int i = colEnd; i >= colStart; i--) {
                    res[rowEnd][i] = index++;
                }
            }
            rowEnd--;
            
            if (colStart <= colEnd) {
                for (int i = rowEnd; i >= rowStart; i--) {
                    res[i][colStart] = index++;
                }
            }
            colStart++;
        }
        return res;
    }
}
```
