> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-07-2022-59.md).

# 02/07/2022 59

59\. Spiral Matrix II

Method:

Set four variables left = 0, right = n -1, top = 0, and bottom = n-1 for the result matrix. While left <= right && top <= bottom, use four for loops to each traverse from left to right, from top to bottom, from right to left, and from bottom to top and change these four variables accodingly.&#x20;

Time O(n^2)

Space O(1)

```
   class Solution { 
   public int[][] generateMatrix(int n) { 
   int[][] matrix = new int[n][n]; 
   if(n == 0) return matrix; 
   int left = 0, right = n - 1; 
   int top = 0, bottom = n - 1; 
   int count =  1;
   
    while(left <= right && top <= bottom){
        //traverse from left to right
        for(int j = left; j <= right; j++){
            matrix[top][j] = count++;
        }
        top++;
        //traverse from top to bottom
        for(int i = top; i <= bottom; i++){
            matrix[i][right] = count++;
        }
        right--;
        //traverse from right to left
        for(int j = right; j >= left; j--){
            matrix[bottom][j] = count++;
        }
        bottom--;
        //traverse from bottom to top
        for(int i = bottom; i >= top; i--){
            matrix[i][left] = count++;
        }
        left++;
    }
    return matrix;
    
}
```

}
