gpt4 book ai didi

java - 矩阵旋转

转载 作者:行者123 更新时间:2023-12-02 04:30:24 25 4
gpt4 key购买 nike

各位,我一直在分析以下关于矩阵旋转 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

最佳答案

代码应该是:

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

因为任意matrix任意行的列数是相等的。

在 for 循环中 ret[c][mat.length-1-r]ret[c][M-1-r] last-to-first 列,其中 mat[r][c] 是每行的 first-to-last

关于java - 矩阵旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31555119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com