欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > leetcode48-旋转图像

leetcode48-旋转图像

2025/11/7 5:22:47 来源:https://blog.csdn.net/weixin_45799371/article/details/148555336  浏览:    关键词:leetcode48-旋转图像

leetcode 48
在这里插入图片描述

📌 一、任务背景

我们需要完成一个「原地」旋转二维矩阵 90° 的函数,即在不申请额外空间的前提下,对矩阵进行顺时针旋转


🎯 二、战况分析(逐步拆解)

🔁 1. 层级推进机制

let top = 0, bottom = matrix.length - 1;
while (top < bottom)

我们通过双指针 topbottom 控制当前处理的外层边界,随着每轮旋转推进,内层矩阵会逐步被旋转处理。

✅ 每轮循环对应处理一圈(layer)。


🔄 2. 单圈四点轮换

for (let i = top; i < bottom; i++) {// 每次处理一个四元组的旋转
}

在当前圈中,我们从 topbottom,依次旋转边上的四个点,构成一个“角点旋转”的闭环。


📦 3. 四向角变换核心

我们以 4x4 矩阵为例,分析每一组四点如何轮换位置:

const temp = matrix[top][i]
matrix[top][i] = matrix[bottom - i + top][top]
matrix[bottom - i + top][top] = matrix[bottom][bottom - i + top]
matrix[bottom][bottom - i + top] = matrix[i][bottom]
matrix[i][bottom] = temp

假设我们当前处理如下矩阵的外圈:

1  2  3  4
5        8
9       12
13 14 15 16

某一次 i 的角变换顺序:

  • matrix[top][i] ← matrix[bottom - i + top][top]
  • matrix[bottom - i + top][top] ← matrix[bottom][bottom - i + top]
  • matrix[bottom][bottom - i + top] ← matrix[i][bottom]
  • matrix[i][bottom] ← temp

这构成一个顺时针角点轮换,4 个角点依次完成交换,且不需额外空间。


📊 三、图示说明(逻辑可视化)

以 4x4 举例,原始矩阵如下:

1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16

第一圈旋转变换如下(用箭头表示轮换顺序):

1 → 13 → 16 → 4 → 1
2 → 9  → 15 → 8 → 2
3 → 5  → 14 → 12 → 3

第二圈(中间层):

6 → 10 → 11 → 7 → 6

通过这样的轮换,矩阵即可原地顺时针旋转 90 度。


四、技术要点总结

  • ✅ 使用双指针 topbottom 管理每层的上下边界。
  • ✅ 每轮处理一圈中的所有角点组,每组做四次顺时针变换。
  • ✅ 全程原地操作,无需额外数组空间。
  • ✅ 时间复杂度:O(n²),空间复杂度:O(1)。

参考视频:https://www.bilibili.com/video/BV1FaHbecE9V/?spm_id_from=333.337.search-card.all.click&vd_source=ccb42000243a376a86b435878466ec00

实现

var rotate = function (matrix) {let top = 0, bottom = matrix.length - 1;while (top < bottom) {for (let i = top; i < bottom; i++) {// 第一次角变换const temp = matrix[top][i]matrix[top][i] = matrix[bottom - i + top][top]// // 第二次角变换matrix[bottom - i + top][top] = matrix[bottom][bottom - i + top]// // 第三次角变换matrix[bottom][bottom - i + top] = matrix[i][bottom]// // 第四次角变换matrix[i][bottom] = temp}top++bottom--}return matrix
}

📌 更多思考

  • 能否改为先转置矩阵左右镜像实现?
  • 若矩阵不是正方形该如何处理?
  • 若允许额外空间,有哪些更简单的实现方式?

欢迎在评论区交流你的看法 🙌

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词