我想把矩阵旋转90度,我也想把行转成列,把列转成行,我想先旋转外部,内部,中间保持不变,因为它应该是5x5。不管怎么说,我不知道该怎么做。
static int[][] multi = {
{ 3, 4, 5, 6, 7 },
{ 5, 4, 5, 6, 7 },
{ 6, 4, 5, 6, 7 },
{ 8, 4, 5, 6 ,7 },
{ 8, 4 ,5 ,6 ,7 }
};
public static void Rotate_90_Degrees() {
int temp = 0;
for(int i = 0; i < 5; i++) {
multi[i][0] = temp;
for(int j = 0; j < 5; j++) {
temp = multi[0][j];
}
}
}我想要遍历行,创建一个临时变量,然后当我到达列时,我会用临时变量替换它,循环应该会继续。你说呢?
发布于 2019-03-24 02:06:30
提示:
如果您想就地执行循环,您会注意到数据移动是四向交换,如下所示:
M[i,j] -> M[n+1-j,i] -> M[n+1-i,n+1-j] -> M[j,n+1-i] -> M[i,j]发布于 2019-03-24 03:21:18
我创建了一个算法,将矩阵向右旋转90°。如果你想向左旋转,你可以简单地向右旋转3次(当然,如果你不关心性能:)。如果您只需要旋转NxN矩阵,那么您可以就地进行。为了简单起见,我没有在算法中包含这种情况。
我使用String作为矩阵原语类型,这样我们可以更好地看到输出单元格。当然,你也可以用int做同样的事情作为基类型。
import java.util.Arrays;
public class YouSpinMyHeadRightRound
{
/**
* Rotates the matrix by 90 degrees. Input needs to
* be a "m x n" matrix.
*/
public static String[][] rotateRightBy90Degrees(String[][] inputMatrix)
{
int rows, columns;
rows = inputMatrix.length;
columns = inputMatrix[0].length;
int outputRows, outputColumns;
outputRows = columns;
outputColumns = rows;
String[][] output = new String[outputRows][outputColumns];
// fill the output matrix
for (int i = 0; i < outputColumns; i++)
{
for (int j = 0; j < outputRows; j++)
{
output[j][outputColumns - 1 - i] = inputMatrix[i][j];
}
}
return output;
}
/**
* Prints the matrix to console.
*/
public static void printMatrixToConsole(String[][] input)
{
for (int i = 0; i < input.length; i++)
{
System.out.println(Arrays.toString(input[i]));
}
}
/*
* For testing purposes!
*/
public static void main(String[] args)
{
String[][] matrixA = new String[][] {{"00", "01", "02", "03"},
{"10", "11", "12", "13"}, {"20", "21", "22", "23"}};
String[][] rotated90 = YouSpinMyHeadRightRound
.rotateRightBy90Degrees(matrixA);
String[][] rotated180 = YouSpinMyHeadRightRound
.rotateRightBy90Degrees(rotated90);
String[][] rotated270 = YouSpinMyHeadRightRound
.rotateRightBy90Degrees(rotated180);
String[][] rotated360 = YouSpinMyHeadRightRound
.rotateRightBy90Degrees(rotated270);
System.out.println("Initial matrix: ");
YouSpinMyHeadRightRound.printMatrixToConsole(matrixA);
System.out.println();
System.out.println("90° to the right:");
YouSpinMyHeadRightRound.printMatrixToConsole(rotated90);
System.out.println("180° to the right:");
YouSpinMyHeadRightRound.printMatrixToConsole(rotated180);
System.out.println("270° to the right:");
YouSpinMyHeadRightRound.printMatrixToConsole(rotated270);
System.out.println("360° to the right:");
YouSpinMyHeadRightRound.printMatrixToConsole(rotated360);
// the 360° matrix matches with matrixA
}
}输出为:
Initial matrix:
[00, 01, 02, 03]
[10, 11, 12, 13]
[20, 21, 22, 23]
90° to the right:
[20, 10, 00]
[21, 11, 01]
[22, 12, 02]
[23, 13, 03]
180° to the right:
[23, 22, 21, 20]
[13, 12, 11, 10]
[03, 02, 01, 00]
270° to the right:
[03, 13, 23]
[02, 12, 22]
[01, 11, 21]
[00, 10, 20]
360° to the right:
[00, 01, 02, 03]
[10, 11, 12, 13]
[20, 21, 22, 23]https://stackoverflow.com/questions/55316789
复制相似问题