【问题标题】:Flipping a 2D array matrix horizontally水平翻转二维数组矩阵
【发布时间】:2020-01-21 19:40:45
【问题描述】:

我正在尝试为经典问题寻找替代解决方案:

给定一个 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

是什么导致我的解决方案出现错误?

【问题讨论】:

  • 你确实是对的。旋转和转置矩阵将导致矩阵镜像。研究此类事物的数学领域称为群论。
  • 请先修改矩阵,再打印出来。

标签: java matrix multidimensional-array


【解决方案1】:

如果您知道经典解决方案以及它是多么简单,即简单的行翻转,您为什么还要开始考虑任何必须处理单个单元格的解决方案?这将浪费处理能力并增加不必要的代码复杂性。

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]]

【讨论】:

  • 据我了解(尽管不可否认,它并不完全清楚......)其意图正是 不是 翻转矩阵,而是旋转它。甚至可能涵盖完整的en.wikipedia.org/wiki/Dihedral_group_of_order_8 ...
  • @Marco13 补充一点,我不会从原始位置移动任何行或列。我实际上是在查看像这样 [column][row] 而不是 [row][column] 的矩阵。意思是,在 [2][0] = 3。[1][0] = 2 [0][0] = 1
猜你喜欢
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 2020-03-19
相关资源
最近更新 更多