Reputation:
folks, I've been analyzing the following code about the rotation of matrix by 90 degrees:
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;
}
The code works fine.
What I do not understand is why c < mat[0].length
Shouldn't it be c < mat[i].length
?
Upvotes: 0
Views: 526
Reputation: 5619
The code should be:
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
ret[c][M-1-r] = mat[r][c];
...
Because using M
and N
is faster, saving indirection of storage access.
Also note that:
final int M = mat.length; // number of rows
final int N = mat[0].length; // number of columns
Because the number of columns in any row of any matrix is equal.
In the for loops ret[c][mat.length-1-r]
or ret[c][M-1-r]
is the last-to-first column for each row, where mat[r][c]
is the is the first-to-last column for each row
Upvotes: 1
Reputation: 1648
They are checking the length of the matrix. Since the length is the same, the solution is correct. It certainly shouldn't be c < mat[i].length
because i
is not known in the scope, it should be (as it is) c < mat[0].length
or better yet: c < N
.
Upvotes: 0
Reputation: 393821
A matrix has the same length for all rows (i.e. the same number of columns in each row), so if mat
is a matrix, mat[0].length
is equal to mat[i].length
for any i
from 0
to mat.length-1
. Therefore it doesn't matter if you write mat[i].length
or mat[0].length
.
Upvotes: 1