# C++ 4ms easy to understand solution. Just a tweak from Spiral Matrix solution

• Here is my solution for Spiral Matrix: https://leetcode.com/discuss/55320/c-0ms-very-straightforward-solution-using-direction. There were just a few changes from my Spiral Matrix solution. The changes are commented.

Below is my solution for Spiral Matrix 2:

enum Direction
{
LEFT,
RIGHT,
UP,
DOWN
};

vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> result(n, vector<int>(n)); // changed

int left = -1;
int right = n; // changed
int top = -1;
int bottom = n; // changed

// hope total size do not overflow
int totalSize = n * n; // changed

int curRow = 0;
int curCol = 0;
Direction dir = RIGHT;
for (int i = 1; i <= totalSize; i++) // changed
{
result.at(curRow).at(curCol) = i; // changed
if (dir == RIGHT)
{
if (curCol+1 == right)
{
top++;
dir = DOWN;
curRow++;
}
else
{
curCol++;
}
}
else if (dir == DOWN)
{
if (curRow+1 == bottom)
{
right--;
dir = LEFT;
curCol--;
}
else
{
curRow++;
}
}
else if (dir == LEFT)
{
if (curCol-1 == left)
{
bottom--;
dir = UP;
curRow--;
}
else
{
curCol--;
}
}
else
{
if (curRow-1 == top)
{
left++;
dir = RIGHT;
curCol++;
}
else
{
curRow--;
}
}
}
return result;
}

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