[英]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
是矩陣,則對於從0
到mat.length-1
任何i
, mat[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];
...
因為使用M
和N
更快,所以可以節省存儲訪問的間接訪問。
另請注意:
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.