Question: Rotate MXN matrix clockwise by 90 degree
Approach:
Observation
first row of source ------> last column of destination second row of source ------> last but-one column of destination so ... on last row of source ------> first column of destination
n = number of rows and columns (rows==columns, square matrix)
i = line
j = column
a[ ][ ] and b[ ][ ] = the matrixes
i = line
j = column
a[ ][ ] and b[ ][ ] = the matrixes
And the instructions:
for(i=0; i<m; i++)
for(j=0; j<n; j++)
b[j][m-i-1]=a[i][j];
for(j=0; j<n; j++)
b[j][m-i-1]=a[i][j];
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public int [][] rotateMatrix( int [][] a, int m, int n) { int [][] b = new int [m][n]; for ( int i= 0 ; i<m; i++) { for ( int j= 0 ; j<n; j++) { b[j][m-i- 1 ] = a[i][j]; } } return b; } |
No comments:
Post a Comment