# Very simple solution using clockwise direction variable

• In case anyone is interested in a simple direction based solution...

``````class Solution {
public:
vector<vector<int> > generateMatrix(int n) {

vector<vector<int> > res(n, vector<int>(n, 0));

if( n == 1 )
res[0][0] = 1;

if(n <= 1)
return res;

int dx[] = {0, 1, 0,-1}, dy[] = {1, 0,-1, 0};
int d = 0, i = 0, j = 0, v = 1;

while(true){
res[i][j] = v++;

if( i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ])
d = (d+1)%4;

i += dx[d], j += dy[d];

if(res[i][j])
break;
}
return res;
}
};``````

• I think it is good answer with zero as unreached position

• Need to change if( i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ]) to:
if(i+dx[d]<0 || j+dy[d]<0 || i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ])

• Not really. It's making a clockwise spiral like turn, never trying to reach the 0 boundary, given n > 1.

• The most outer bottom layer will reach out to 0 boundary.

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