Blind 75
Rotate Image
- Problem
- LC 48
- Category
- Matrix
- File
- blind75_LC48RotateImage.java
- Path
- pkg5leetcode/blind75/blind75_LC48RotateImage.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC48RotateImage.java
- Approach
- Transpose then reverse each row for 90° clockwise.
- Complexity
- Time O(n^2), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Rotate Image | LC 485 * APPROACH: Transpose then reverse each row for 90° clockwise.6 * COMPLEXITY: Time O(n^2), Space O(1)7 */8public class blind75_LC48RotateImage {9 static void rotate(int[][] matrix) {10 int n = matrix.length;11 for (int i = 0; i < n; i++)12 for (int j = i + 1; j < n; j++) {13 int t = matrix[i][j];14 matrix[i][j] = matrix[j][i];15 matrix[j][i] = t;16 }17 for (int i = 0; i < n; i++)18 for (int lo = 0, hi = n - 1; lo < hi; lo++, hi--) {19 int t = matrix[i][lo];20 matrix[i][lo] = matrix[i][hi];21 matrix[i][hi] = t;22 }23 }24 25 public static void main(String[] args) {26 int[][] m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};27 rotate(m1);28 check(m1[0][0] == 7 && m1[0][2] == 1 && m1[2][0] == 9, "case1");29 int[][] m2 = {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};30 rotate(m2);31 check(m2[0][0] == 15 && m2[3][3] == 11, "case2");32 System.out.println("all tests passed");33 }34 35 static void check(boolean cond, String name) {36 if (!cond) throw new AssertionError("FAILED: " + name);37 System.out.println(" PASS " + name);38 }39}