Last active
October 13, 2015 07:38
-
-
Save hokamoto/4162106 to your computer and use it in GitHub Desktop.
Rotate images by 90 degrees in place.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package questions; | |
public class Questions1_6 { | |
public static void main(String[] args) { | |
// initialize matrix | |
final int N = 10; | |
int[][] matrix = new int[N][N]; | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < N; j++) { | |
matrix[i][j] = i * 10 + j; | |
} | |
} | |
showMatrix(matrix); | |
System.out.print("\n"); | |
rotateMatrix(matrix); | |
System.out.print("\n"); | |
showMatrix(matrix); | |
} | |
public static void rotateMatrix(int[][] matrix) { | |
int N = matrix.length - 1; | |
for (int r = 0; r <= N / 2; r++) { | |
for (int x = 0; x < N - 2 * r; x++) { | |
int tmp = matrix[r + x][r]; | |
matrix[r + x][r] = matrix[r][N - x - r]; | |
matrix[r][N - x - r] = matrix[N - x - r][N - r]; | |
matrix[N - x - r][N - r] = matrix[N - r][r + x]; | |
matrix[N - r][r + x] = tmp; | |
} | |
} | |
} | |
public static void showMatrix(int[][] matrix) { | |
for (int i = 0; i < matrix.length; i++) { | |
for (int j = 0; j < matrix[i].length; j++) { | |
System.out.print(String.format("%02d", matrix[j][i]) + ' '); | |
} | |
System.out.print("\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment