【发布时间】:2013-04-05 16:40:32
【问题描述】:
我有一个需要逆时针旋转 90 度的二维矩阵 M[N][N]。我已经看到很多顺时针旋转的答案,但我找不到逆时针方向。这两个操作有多相似?
【问题讨论】:
我有一个需要逆时针旋转 90 度的二维矩阵 M[N][N]。我已经看到很多顺时针旋转的答案,但我找不到逆时针方向。这两个操作有多相似?
【问题讨论】:
如果您颠倒每个单独行的顺序,然后以与顺时针旋转相反的顺序取行,则会得到逆时针旋转。
A B C G D A A D G C F I
D E F -> Clockwise -> H E B -> Reverse -> B E H -> Opposite -> B E H
G H I I F C Rows C F I Ordering A D G
Matrix Counter
Clockwise
如果您已经有可用的顺时针旋转算法,通常以相反的顺序对原始矩阵进行顺时针旋转会更容易(并且计算效率更高)。
1 2 3 9 8 7 3 6 9
4 5 6 -> Reverse -> 6 5 4 -> Clockwise -> 2 5 8
7 8 9 Indices 3 2 1 1 4 7
Matrix Counter
Clockwise
你也可以顺时针旋转 3 圈来逆时针旋转。
尽管在现实中,根据您的目的直接编辑顺时针算法通常相当容易。因此,如果您不关心效率并且不想通过更改旋转方向的逻辑来工作,我只会使用上述选项。
【讨论】:
从行(最大)开始,递减,用该列的值逐个(递增)填充结果行(递增索引)。
所以在 3 x 3 中,使用(使用 r、c 符号,如 Excel)
(3, 1), (3, 2), (3, 3), (2, 1), (2, 2), (2, 3),
等等
【讨论】:
如果您使用特定的矩阵库,您可以只进行 3 次转置
【讨论】:
好的。让我们简单地说N =2:
1 2
3 4
逆时针90度表示会变成:
2 4
1 3
我们有以下规则:
1 last column from top to bottom of original matrix becomes
first row of rotated matrix from left to right
2 first column of original matrix becomes last row of rotated matrix
3 same rules apply to other columns of original matrix
您可以轻松编写代码。 另一种方法是先对矩阵进行转置,然后反转所有行的顺序。
【讨论】:
public static void main(String[] args) {
int[][] matrix = createAMatrix(3,3);
List<Stack<Integer>> tiltedMatrix = tiltMatrixBy90Now(matrix, 3);
int[][] newMatrix = new int[3][3];
for(int i = 0; i < 3; i ++) {
for(int j = 0; j < 3; j ++) {
newMatrix[i][j] = tiltedMatrix.get(j).pop();
}
}
//print new matrix
for(int i = 0; i < 3; i ++) {
for(int j = 0; j < 3; j ++) {
System.out.print(newMatrix[i][j]+" ");
}
System.out.println();
}
}
private static List<Stack<Integer>> tiltMatrixBy90Now(int[][] matrix , long order) {
List<Stack<Integer>> stackList = new ArrayList<>();
//filling the stack
for(int i = 0; i< order ; i++) {
stackList.add(new Stack<Integer>());
}
for(int i = 0; i < order; i ++) {
for(int j = 0; j < order; j ++) {
stackList.get(i).push(matrix[i][j]);
}
}
return stackList;
}
private static int[][] createAMatrix(final int a, final int b){
int counter = 1;
int[][] matrix = new int[a][b];
Scanner scanner = new Scanner(System.in);
while(counter <= a*b) {
for(int i = 0; i < a; i ++) {
for(int j = 0; j < b; j ++) {
matrix[i][j] = scanner.nextInt();
counter++;
}
}
}
return matrix;
}
/*
输入矩阵(3乘3) 1 2 3 4 5 6 7 8 9
输出矩阵(3乘3): 3 6 9 2 5 8 1 4 7
代码演练作为文本解释
*/
【讨论】: