# Why my c++ code is runtime error?

• ``````class Solution {
public:
int direction(vector<vector<int> > temp, int i, int j, int n, int next_step){
if(next_step == 1){
if(j < n-1)
if(temp[i][j+1] == 0)
return 1;//left
}
if(next_step == 2){
if(i < n-1)
if(temp[i+1][j] == 0)
return 2;//down
}
if(next_step == 3){
if(j > 0)
if(temp[i][j-1] == 0)
return 3;//right
}
if(next_step == 4){
if(i > 0)
if(temp[i-1][j] ==0)
return 4;//up
}

if(j < n-1)
if(temp[i][j+1] == 0)
return 1;//left
if(i < n-1)
if(temp[i+1][j] == 0)
return 2;//down
if(j > 0)
if(temp[i][j-1] == 0)
return 3;//right
if(i > 0)
if(temp[i-1][j] ==0)
return 4;//up

return 0;
}

vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > resl;
for(int i = 0; i < n ; i++){
vector<int> temp;
for(int j = 0; j < n; j++){
temp.push_back(0);
}
resl.push_back(temp);
temp.clear();
}
int x=0,y=0;
resl[x][y]=1;
int next_step = 1;
for(int i = 2; i < n*n+1 ;i++){
next_step = direction(resl,x,y,n,next_step);
switch(next_step){
case 1:{y++;break;}
case 2:{x++;break;}
case 3:{y--;break;}
case 4:{x--;break;}
}
resl[x][y] = i;

}
return resl;
}

};``````

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