# My 6ms solution

• Starting by filling the matrix on the outmost layer
Example:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

`````` 1   2 3 4
12 0 0 5
11 0 0 6
10 9 8 7
``````

An call again on the inner layer until all layers are filed.

``````class Solution {
public:

void fillMatrix(vector<vector<int> > &matrix, int start_row, int start_column, int n, int &start_value) {
for(int j = start_column; j < n - start_column; j++) {
matrix[start_row][j] = start_value;
start_value++;
}
start_value--;

for(int j = start_row; j < n - start_row; j++) {
matrix[j][n - start_column - 1] = start_value;
start_value++;
}

start_value--;

for(int j = n-start_column-1; j >= start_column; j--) {
matrix[n-start_row-1][j] = start_value;
start_value++;
}

start_value--;

for(int j = n-start_row -1; j > start_row; j--) {
matrix[j][start_column] = start_value;
start_value++;
}

}

vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n, vector<int>(n, 0));

int start_value = 1;
int middle = 0;
int max_fil = n / 2;

if(n % 2 == 1)
max_fil = max_fil + 1;

for(int i = 0; i < max_fil; i++) {
fillMatrix(matrix, i, i, n, start_value);

}

return matrix;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.