@@ -26,4 +26,50 @@ You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-pla
2626
2727* ` n == matrix.length == matrix[i].length `
2828* ` 1 <= n <= 20 `
29- * ` -1000 <= matrix[i][j] <= 1000 `
29+ * ` -1000 <= matrix[i][j] <= 1000 `
30+
31+ To solve the "Rotate Image" problem in Java with a ` Solution ` class, we can follow these steps:
32+
33+ 1 . Define a ` Solution ` class.
34+ 2 . Define a method named ` rotate ` that takes a 2D array ` matrix ` representing an image as input and rotates the image by 90 degrees clockwise.
35+ 3 . Determine the number of layers in the matrix, which is equal to half of the matrix's size.
36+ 4 . Iterate through each layer from outer to inner layers.
37+ 5 . For each layer:
38+ - Iterate through each element in the current layer.
39+ - Swap the elements of the current layer in a clockwise manner.
40+ 6 . Return the rotated matrix.
41+
42+ Here's the implementation:
43+
44+ ``` java
45+ public class Solution {
46+ public void rotate (int [][] matrix ) {
47+ int n = matrix. length;
48+ int layers = n / 2 ;
49+
50+ for (int layer = 0 ; layer < layers; layer++ ) {
51+ int first = layer;
52+ int last = n - 1 - layer;
53+
54+ for (int i = first; i < last; i++ ) {
55+ int offset = i - first;
56+ int top = matrix[first][i];
57+
58+ // Move left to top
59+ matrix[first][i] = matrix[last - offset][first];
60+
61+ // Move bottom to left
62+ matrix[last - offset][first] = matrix[last][last - offset];
63+
64+ // Move right to bottom
65+ matrix[last][last - offset] = matrix[i][last];
66+
67+ // Move top to right
68+ matrix[i][last] = top;
69+ }
70+ }
71+ }
72+ }
73+ ```
74+
75+ This implementation provides a solution to the "Rotate Image" problem in Java. It rotates the given 2D matrix representing an image by 90 degrees clockwise in-place.
0 commit comments