我正在尝试解决将矩阵旋转90度的问题。到目前为止,这是我的解决方案:
static int[][] rotateImage(int[][] a) {
for(int i = 0; i < a.length; ++i) {
for(int j = 0; j < i; ++j) {
int temp_ji = a[j][i];
a[j][i] = a[i][j];
a[i][j] = temp_ji;
}
}
int columnA = 0;
int columnB = a.length-1;
while(columnA != columnB)
{
swapColumns(a, columnA, columnB);
columnA++; columnB--;
if(columnA == 10)
{
break;
}
}
return a;
}
static void swapColumns(int a[][], int cA, int cB)
{
String s = "";
for (int i = 0; i < a.length; i++) {
int temp_ij = a[i][cB];
a[i][cB] = a[i][cA];
a[i][cA] = temp_ij;
s = s + " " + a[i][cA];
System.out.println(s);
}
}
我没有理解为什么我的代码在我有这个条目时没有正确地交换列:
int a[][] = new int[][]{
{40,12,15,37,33,11,45,13,25,3},
{37,35,15,43,23,12,22,29,46,43},
{44,19,15,12,30,2,45,7,47,6},
{48,4,40,10,16,22,18,36,27,48},
{45,17,36,28,47,46,8,4,17,3},
{14,9,33,1,6,31,7,38,25,17},
{31,9,17,11,29,42,38,10,48,6},
{12,13,42,3,47,24,28,22,3,47},
{38,23,26,3,23,27,14,40,15,22},
{8,46,20,21,35,4,36,18,32,3}
};
a = rotateImage(a);
非常感谢任何帮助。
这是问题的原始表述:
您将获得一个代表图像的n x n 2D矩阵。将图像旋转90度(顺时针)。
实施例
有关
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
输出应为
rotateImage(a) =
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
答案 0 :(得分:0)
解决。这是正确的条件:
int counter = 0;
while(counter < (a.length / 2))
{
swapColumns(a, columnA, columnB);
columnA++; columnB--;
counter++;
}