我需要编写一个代码来转换转换矩阵,我无法做到,程序只能替换一些位置而其他位置保持不变。对这个问题有任何想法吗?
我需要使用任何矩阵nxn
public static int [][] getTransposed(int matrix[][], int initRow, int endRow, int initColumn, int endColumn, int totalSize) {
if (endRow - initRow <= 2 && endColumn - initColumn <= 2) {
return invertPosition(matrix, initRow, endRow, initColumn, endColumn);
} else {
int mediumRow = (initRow + endRow) / 2;
int mediumColumn = (initColumn + endColumn) / 2;
getTransposed(matrix, initRow, mediumRow, initColumn, mediumColumn, totalSize);
getTransposed(matrix, initRow, mediumRow, mediumColumn, endColumn, totalSize);
}
return matrix;
}
private static int [][] invertPosition(int matrix[][], int initRow, int endRow, int initColumn, int endColumn) {
int temp;
for (int r = initRow; r < endRow; r++) {
for (int c = initColumn; c < endColumn; c++) {
temp = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = temp;
}
}
return matrix;
}
答案 0 :(得分:0)
我建议在 nxn Matrix 的 Transpose > Java 通过利用ArrayList
等可用类。我会做这样的事情:
import java.util.ArrayList;
import java.util.List;
public class MatrixTranspose{
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; // 3x3 square matrix
int[][] matrix1 = {{1,2}}; // one row
int[][] matrix2 = {{1},{4},{7}}; // one column
int[][] matrix3 = {{1,2,3},{4,5,6}}; // 2x3 matrix
int[][] matrix4 = {{1,2},{3,4},{5,6},{7,9}}; // 4x2 matrix
// testing
printTranspose(transpose(matrix));
printTranspose(transpose(matrix1));
printTranspose(transpose(matrix2));
printTranspose(transpose(matrix3));
printTranspose(transpose(matrix4));
}
public static void printTranspose(int [][] transpose){
for(int i=0; i<transpose.length ; i++, System.out.println()){
for(int j=0; j<transpose[0].length; j++){
System.out.print(transpose[i][j] + "\t");
}
}
System.out.println("-------------------------");
}
public static int[][] transpose(int[][] matrix){
// ArrayList to collect every column
ArrayList<Integer> oneColumn = new ArrayList<Integer>();
// ArrayList to collect all Columns
List<ArrayList<Integer>> columns = new ArrayList<ArrayList<Integer>>();
// take the dimension of the array
int rs = matrix.length;
int cols = matrix[0].length;
// start collecting the elements
for(int i=0; i<rs ; i++){
for(int j=0; j<cols; j++){
oneColumn.add(matrix[i][j]);
}
columns.add(oneColumn);
oneColumn = new ArrayList<Integer>();
}
// create array for the final result (transpose)
int[][] result = new int[cols][rs];
// start converting the columns to rows and collect them
for(int i=0; i<cols ; i++){
for(int j=0; j<rs; j++){
result[i][j] = columns.get(j).get(i);
}
}
return result;
}
}
<强>输出强>
1 4 7
2 5 8
3 6 9
-------------------------
1
2
-------------------------
1 4 7
-------------------------
1 4
2 5
3 6
-------------------------
1 4 6 8
2 5 7 9
-------------------------