# Spiral Matrix II

## Opposite to Spiral Matrix I

`Spiral Matrix I`

is a reader, it reads numbers from the matrix.

`Spiral Matrix II`

is a writer, it writes numbers into the matrix.

### Source code *Read on Github*

```
1 public class Solution {
2 public int[][] generateMatrix(int n) {
3 // Note: The Solution object is instantiated only once and is reused by each test case.
4
5 int[][] rt = new int[n][n];
6 if(n <= 0) return rt;
7
8 int c = 1;
9
10 int x = 0, y = 0, my = n , mx = n;
11
12 while(x < mx && y < my){
13 for(int i = x; i < mx && y < my; i++){
14 rt[y][i] = c++;
15 }
16
17 y++;
18
19 for(int i = y; i < my && x < mx ; i++ ){
20 rt[i][mx - 1] = c++;
21 }
22
23 mx--;
24
25 for(int i = mx - 1; i >= x && y < my; i--){
26 rt[my - 1][i] = c++;
27 }
28
29 my--;
30
31 for(int i = my - 1; i>= y && x < mx; i--){
32 rt[i][x] = c++;
33 }
34
35 x++;
36
37 }
38
39 return rt;
40
41
42 }
43 }
```