[英]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.