# C++ code, classical method, use your A4 paper and put a mark on it, you will see the trick

• Get 2 blank papers, take a pen and write 1, 2, 3, 4 on each corner of the papers. 1 for top left, 2 for top right, etc, it does not matter which corner takes which number. But 2 papers must be marked the same way.

1/ Now take the first paper, rotate it clockwise 90 degree, leave it there.

2/ Take the second paper, flip it through the middle horizontal line:

``````for (int i=0; i<m/2; i++)
swap(matrix[i], matrix[m-1-i]);
``````

Then one hand holds top left corner, the other hand holds bottom right corner, flip the paper in such a way that top left corner becomes bottom right corner.

``````for (int i=0; i<m; i++)
for (int j=0; j<i; j++)
swap(matrix[i][j], matrix[j][i]);
``````

Compare the 2 papers, they are the same.

Full code:

``````void rotate(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
for (int i=0; i<m/2; i++)
swap(matrix[i], matrix[m-1-i]);
for (int i=0; i<m; i++)
for (int j=0; j<i; j++)
swap(matrix[i][j], matrix[j][i]);
}``````

``````for (int i=0; i<m/2; i++)
swap(matrix[i], matrix[m-1-i]);
``````

• Hi, thank you for suggesting. I did not know this would work. Is this why I get downvotes?

• As far as I know you can swap two collections of the same type in C++, if `swap(a, b)` fails maybe `a.swap(b)`.
I don't think this would warrant a down vote, maybe it's your title or the fact the it's a code-only post.

• Thank you very much! I fixed the code and it worked. I don't know what else I can write though, since the title tells everything already. :(

• Well, you could elaborate on it, for example explain the trick, because I don't get it either. I see flip+transpose, but don't get how A4 comes in.

• I see. I will add it now. Thank you for commenting. :D

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