# My AC solution with using direction variable

• `````` vector<vector<int> > generateMatrix(int n) {
int dir = 0;
vector< vector<int> > matrix(n, vector<int> (n, 0));
int i = 0, j = 0, k = 1;
while (k <= n * n) {
matrix[i][j] = k++;
if (dir == 0){
j++;
if (j == n || matrix[i][j] != 0) dir = 1, j--, i++;
} else
if (dir == 1) {
i++;
if (i == n || matrix[i][j] != 0) dir = 2, i--, j--;
} else
if (dir == 2) {
j--;
if (j < 0 || matrix[i][j] != 0) dir = 3, j++, i--;
} else
if (dir == 3) {
i--;
if (i < 0 || matrix[i][j] != 0) dir = 0, i++, j++;
}
}
return matrix;
}``````

• Nice code! O(mn) solution!

• Your code is very nice and neat. I rewrite in Java with switch-case statement. One improvement I did is to put the logic of changing direction in one place, so that if we want to print the matrixx counter-clock
wise, then we just need to change the initial direction and the logic to change direction.

``````public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if (n==0) {
return matrix;
}
int prevValue = 0;
int prevRow = 0;
int prevCol = -1;
int direction = 0;
while (prevValue < n*n) {
boolean changeDirection = false;
switch (direction) {
case 0:
if (prevCol < n-1 && matrix[prevRow][prevCol+1] == 0) {
matrix[prevRow][++prevCol]=++prevValue;
} else {
changeDirection = true;
}
break;
case 1:
if (prevRow < n-1 && matrix[prevRow+1][prevCol] == 0) {
matrix[++prevRow][prevCol]=++prevValue;
} else {
changeDirection = true;
}
break;
case 2:
if (prevCol > 0 && matrix[prevRow][prevCol-1] == 0) {
matrix[prevRow][--prevCol]=++prevValue;
} else {
changeDirection = true;
}
break;
case 3:
if (prevRow > 0 && matrix[prevRow-1][prevCol] == 0) {
matrix[--prevRow][prevCol]=++prevValue;
} else {
changeDirection = true;
}
}
if (changeDirection) {
direction = (direction + 1)%4;
}
}

return matrix;
}
``````

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

``````    vector<vector<int>> res(n,vector<int> (n,0));
int colL=0,rowL=0;
int colH=n-1;
int rowH=n-1;
int k=1;
while(colL<=colH&&rowL<=rowH){

for(int i=colL;i<=colH;++i ){

res[rowL][i]=k++;

}

rowL++;
for(int i=rowL;i<=rowH;++i){

res[i][colH]=k++;

}
colH--;

for(int i=colH;i>=colL;--i){

res[rowH][i]=k++;
}

rowH--;
for(int i=rowH;i>=rowL;--i){

res[i][colL]=k++;

}
colL++;

}

return res;
}
``````

};

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