[英]how to rotate a sub-matrix NxN by 90 degree clockwise in a bigger AxB matrix - in Java
每個人。 我正在嘗試在更大的 AxB 矩陣中將子矩陣 NxN 順時針旋轉 90 度。 我發現的大多數答案只涉及整個矩陣 NxN。 下面是示例。
給定一個 A x B 矩陣,將一個子矩陣 NxN 順時針旋轉 90 度。
給定 [3 x 4] 矩陣的樣本輸入將子矩陣 [3 x 3] 順時針旋轉 90 度。
0 [1 2 3 ] 4
5 [6 7 8 ] 9
10 [11 12 13] 14
預期 output
0 [11 6 1] 4
5 [12 7 2] 9
10 [13 8 3] 14
如果有人可以幫助我,我真的很感激。 謝謝 !
嘗試這個。
top
和left
是子矩陣左上角的坐標。 n
是子矩陣的大小。
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;
}
和
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.