Reputation: 1
everyone ! I'm trying to rotate sub-matrix NxN for 90 degree clockwise within a bigger AxB matrix. Most answers I found is only dealt with a whole matrix NxN. Below is the example.
Given a A x B matrix rotate a sub-matrix NxN for 90 degree clockwise.
Sample input given [3 x 4] matrix rotate sub-matrix [3 x 3] for 90 degree clockwise.
0 [1 2 3 ] 4
5 [6 7 8 ] 9
10 [11 12 13] 14
Expected output
0 [11 6 1] 4
5 [12 7 2] 9
10 [13 8 3] 14
Really appreciate if someone can help me out. Thanks !
Upvotes: 0
Views: 286
Reputation:
Try this.
top
and left
are the coordinates of the upper left corner of the submatrix.
n
is the size of the submatrix.
static int[][] rotate(int[][] a, int top, int left, int n) {
int height = a.length, width = a[0].length;
int[][] b = new int[height][];
for (int x = 0; x < height; ++x)
b[x] = Arrays.copyOf(a[x], width);
for (int x = top, xmax = top + n, ty = left + n - 1; x < xmax; ++x, --ty)
for (int y = left, ymax = left + n, tx = 0; y < ymax; ++y, ++tx)
b[tx][ty] = a[x][y];
return b;
}
And
int[][] a = {
{0, 1, 2, 3, 4},
{5, 6, 7, 8, 9},
{10, 11, 12, 13, 14},
};
int[][] b = rotate(a, 0, 1, 3);
for (int[] row : b)
System.out.println(Arrays.toString(row));
output:
[0, 11, 6, 1, 4]
[5, 12, 7, 2, 9]
[10, 13, 8, 3, 14]
Upvotes: 1