簡體   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