繁体   English   中英

矩阵旋转

[英]Matrix rotation

伙计们,我一直在分析以下有关矩阵旋转90度的代码:

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 < mat.length; r++) {
        for (int c = 0; c < mat[0].length; c++) {
            ret[c][mat.length-1-r] = mat[r][c];
        }
    }
    return ret;
}

该代码工作正常。 我不明白的是为什么c < mat[0].length不应该是c < mat[i].length吗?

矩阵的所有行的长度相同(即每行中的列数相同),因此,如果mat是矩阵,则对于从0mat.length-1任何imat[0].length等于mat[i].length mat.length-1 因此,无论您写mat[i].length还是mat[0].length都没关系。

代码应为:

for (int r = 0; r < M; r++) {
    for (int c = 0; c < N; c++) {
        ret[c][M-1-r] = mat[r][c]; 
        ...

因为使用MN更快,所以可以节省存储访问的间接访问。

另请注意:

final int M = mat.length; // number of rows
final int N = mat[0].length; // number of columns

因为任何矩阵的任何行中的列数均相等。

在for循环中, ret[c][mat.length-1-r]ret[c][M-1-r]是每行的倒数第一列,其中mat[r][c]是这是每一行的倒数第一

他们正在检查矩阵的长度。 由于长度相同,因此解决方案是正确的。 它肯定不应该是c < mat[i].length因为在范围内不知道i ,它应该是(实际上)是c < mat[0].length或更好: c < N

mat[0].length representing the column length.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM