我正在为经典问题寻找替代解决方案:
给出一个m x n 2D图像矩阵,其中每个整数代表一个像素。沿水平轴将其翻转到位。
之前:
1 2 3
4 5 6
7 8 9
之后:
7 8 9
4 5 6
1 2 3
我知道经典的解决方案,但是想知道是否可以通过将矩阵按顺时针方向旋转来解决?然后,可以假设只对矩阵进行垂直翻转,如下所示。
转弯后:
3 6 9
2 5 8
1 4 7
public static void flipHorizontalAxis(int[][] matrix)
{
for (int column = matrix.length - 1; column > 0; column--)
{
for (int row = 0; row < matrix[0].length / 2; row++)
{
int temp = matrix[column][row];
matrix[column][row] = matrix[column][matrix.length - 1];
matrix[column][matrix[0].length - 1] = temp;
System.out.print(matrix[column][row] + "\t");
}
System.out.println();
}
}
这是我到目前为止的内容,但输出显示:
3 4 7
2 5 8
1 6 9
什么导致我的解决方案中的错误?
答案 0 :(得分:0)
如果您知道经典的解决方案以及它的简单性(即简单的行翻转),为什么还要考虑考虑必须处理单个单元格的任何解决方案?那会浪费处理能力,并增加不必要的代码复杂性。
public static void flipHorizontalAxis(int[][] matrix) {
int last = matrix.length - 1;
for (int i = last / 2; i >= 0; i--) {
int[] temp = matrix[i];
matrix[i] = matrix[last - i];
matrix[last - i] = temp;
}
}
测试
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
flipHorizontalAxis(matrix);
System.out.println(Arrays.deepToString(matrix));
输出
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]