这是一个标准矩阵顺时针旋转代码:
static int[][] rotateCW(int[][] mat) {
final int M = mat.length;
final int N = mat[0].length;
int[][] ret = new int[N][M];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
ret[c][M-1-r] = mat[r][c];
}
}
return ret;
}
请注意以下几点:
- 它提高了引用尺寸的可读性MxN矩阵为
M
and N
- 这是传统的使用方式
r, c
代替i, j
索引矩阵的行和列
- This is not the most robust implementation:
- 并不能确保
mat
是一个有效的MxN矩阵,M>0, N>0
- Use an explicit mapping formula instead of extraneous local variables
这是一个测试工具:
import java.util.Arrays;
//...
static void printMatrix(int[][] mat) {
System.out.println("Matrix = ");
for (int[] row : mat) {
System.out.println(Arrays.toString(row));
}
}
public static void main(String[] args){
int[][] mat = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
printMatrix(mat);
// Matrix =
// [1, 2, 3]
// [4, 5, 6]
int[][] matCW = rotateCW(mat);
printMatrix(matCW);
// Matrix =
// [4, 1]
// [5, 2]
// [6, 3]
}
注意使用for-each http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html循环和java.util.Arrays http://java.sun.com/javase/6/docs/api/java/util/Arrays.html in printMatrix
。如果您经常在 Java 中使用数组,那么您绝对应该熟悉它们。
Java 矩阵库的链接
如果您经常使用矩阵,您可能需要考虑使用专门的矩阵库。
- JAMA: http://math.nist.gov/javanumerics/jama/ http://math.nist.gov/javanumerics/jama/
- UJMP: http://www.ujmp.org/ http://www.ujmp.org/
相关问题
从技术上讲,Java 有数组的数组。确保您了解所有含义。
- 数组数组与多维数组的性能比较 https://stackoverflow.com/questions/2368761/performance-comparison-of-array-of-arrays-vs-multidimensional-arrays
- Java Arrays.equals()回报false对于二维数组。 https://stackoverflow.com/questions/2721033/java-arrays-equals-returns-false-for-two-dimensional-arrays