Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

48. Rotate Image #1

Open
yikaikai opened this issue Apr 27, 2018 · 0 comments
Open

48. Rotate Image #1

yikaikai opened this issue Apr 27, 2018 · 0 comments

Comments

@yikaikai
Copy link
Owner

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:

Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

 void rotate(vector<vector<int>>& matrix) {

int width = matrix[0].size();

    for (int row = 0; row <= (width - 1) / 2; row++) {
        for (int col = row; col < width - 1 - row; col++) {
            int tmp = matrix[row][col];

            matrix[row][col] = matrix[width - 1 - col][row];
            matrix[width - 1 - col][row] = matrix[width - 1 - row][width - 1 - col];
            matrix[width - 1 - row][width - 1 - col] = matrix[col][width - 1 - row];
            matrix[col][width - 1 - row] = tmp;
        }
    }
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant