-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate Matrix
84 lines (63 loc) · 2.59 KB
/
Rotate Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution{
public void rotate(int[][] matrix){
for(int i = 0; i<matrix.length; i++){
for(int j = i; j<matrix[0].length; j++){
int temp =0;
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i =0; i<matrix.length; i++){
for(int j =0; j<matrix.length/2; j++){
int temp = 0;
temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length -1 - j];
matrix[i][matrix.length - 1 -j] = temp;
}
}
}
}
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < (n + 1) / 2; i ++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i];
matrix[j][n - 1 - i] = matrix[i][j];
matrix[i][j] = temp;
}
}
}
}
=====================================
import java.util.* ;
import java.io.*;
import java.util.* ;
import java.io.*;
import java.util.ArrayList;
public class Solution {
public static void rotateMatrix(ArrayList<ArrayList<Integer>> mat, int n, int m) {
// Write your code here.
int t=0,l=0,b=n-1,r=m-1;
while(t<b && l<r)// to iterate for all elements until it reaches center
{
for(int i=t;i<b;i++) // top to bottom
swap(mat ,i,l ,i+1,l);
for(int i=l;i<r;i++) // left to right
swap(mat ,b,i ,b,i+1);
for(int i=b;i>t;i--) // bottom to top
swap(mat ,i,r ,i-1,r);
for(int i=r;i>l+1;i--) // right to left + 1 to avoid 1st element which was swapped earlier during top - bottom
swap(mat ,t,i ,t,i-1);
l++;t++;r--;b--;// to itarate for internal e;ements
}
static void swap(ArrayList<ArrayList<Integer>> mat,Integer i1,Integer j1 ,Integer i2,Integer j2){
Integer t=mat.get(i1).get(j1);
mat.get(i1).set(j1 , mat.get(i2).get(j2) );
mat.get(i2).set(j2 , t);
//wasn't sure if I should take int or Integer so I took Integer as variable; } }
}
}