1. /**
    2. * 48. Rotate Image
    3. * <p>
    4. * You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
    5. * <p>
    6. * 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.
    7. * <p>
    8. * <p>
    9. * <p>
    10. * Example 1:
    11. * <p>
    12. * <p>
    13. * Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
    14. * Output: [[7,4,1],[8,5,2],[9,6,3]]
    15. * Example 2:
    16. * <p>
    17. * <p>
    18. * Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
    19. * Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
    20. * Example 3:
    21. * <p>
    22. * Input: matrix = [[1]]
    23. * Output: [[1]]
    24. * Example 4:
    25. * <p>
    26. * Input: matrix = [[1,2],[3,4]]
    27. * Output: [[3,1],[4,2]]
    28. * <p>
    29. * <p>
    30. * Constraints:
    31. * <p>
    32. * matrix.length == n
    33. * matrix[i].length == n
    34. * 1 <= n <= 20
    35. * -1000 <= matrix[i][j] <= 1000
    36. */
    37. public class Lesson48 {
    38. public static void main(String[] args) {
    39. int len = (int) (Math.random() * 10);
    40. int[][] matrix = new int[len][len];
    41. for (int i = 0; i < len; i++) {
    42. for (int j = 0; j < len; j++) {
    43. matrix[i][j] = (int) (Math.random() * 1000);
    44. }
    45. }
    46. printMatrix(matrix);
    47. new Solution().rotate(matrix);
    48. printMatrix(matrix);
    49. }
    50. private static void printMatrix(int[][] matrix) {
    51. int n = matrix.length;
    52. StringBuilder stringBuilder = new StringBuilder();
    53. stringBuilder.append("[");
    54. for (int i = 0; i < n; i++) {
    55. stringBuilder.append("[");
    56. for (int j = 0; j < n; j++) {
    57. stringBuilder.append(matrix[i][j]).append(j == n -1 ? "" : ",");
    58. }
    59. stringBuilder.append(i == n -1 ? "]" : "],").append("\n");
    60. }
    61. stringBuilder.append("]");
    62. Util.println(stringBuilder);
    63. }
    64. static class Solution {
    65. public void rotate(int[][] matrix) {
    66. int n;
    67. if (matrix == null || (n = matrix.length) == 0 || matrix[0].length != n) {
    68. return ;
    69. }
    70. int[] tempArr = new int[4];
    71. for (int end = n, start = 0; end > 0 && end - start > 1; end--,start = n - end) {
    72. int last = end - 1;
    73. for (int i = start; i < end - 1; i++) {
    74. int offset = (i - start);
    75. tempArr[0] = matrix[start][i];
    76. tempArr[1] = matrix[i][last];
    77. tempArr[2] = matrix[last][last - offset];
    78. tempArr[3] = matrix[last - offset][start];
    79. matrix[start][i] = tempArr[3];
    80. matrix[i][last] = tempArr[0];
    81. matrix[last][last - offset] = tempArr[1];
    82. matrix[last - offset][start] = tempArr[2];
    83. }
    84. }
    85. }
    86. }
    87. }