JavaScript实现非正方形矩阵90度旋转的方法求助
JavaScript实现矩形矩阵90度顺时针旋转(一维数组形式)
核心思路
针对行优先存储的一维数组矩阵,90度顺时针旋转的关键是找到原矩阵元素与旋转后矩阵元素的位置映射关系:
- 原矩阵为
height行 ×width列,旋转后变为width行 ×height列 - 旋转后矩阵的
(newRow, newCol)位置,对应原矩阵的(height - 1 - newCol, newRow)位置 - 再将二维位置转换为一维数组的索引即可完成映射
实现代码
function rotateMatrix90Clockwise(originalArray, width, height) { const newWidth = height; const newHeight = width; const rotatedArray = new Array(originalArray.length); for (let newRow = 0; newRow < newHeight; newRow++) { for (let newCol = 0; newCol < newWidth; newCol++) { // 计算新数组的索引 const newIndex = newRow * newWidth + newCol; // 找到原数组对应的行列 const originalRow = height - 1 - newCol; const originalCol = newRow; // 计算原数组的索引 const originalIndex = originalRow * width + originalCol; // 赋值 rotatedArray[newIndex] = originalArray[originalIndex]; } } return rotatedArray; }
验证你的示例
// 初始矩阵数组 const original = [0,0,0,0,0,0,1,1,1,0,0,0,0,0,0]; // 原矩阵宽度、高度 const width = 5; const height = 3; // 执行旋转 const rotated = rotateMatrix90Clockwise(original, width, height); console.log(rotated); // 输出:[0,0,0,0,1,0,0,1,0,0,1,0,0,0,0] 与目标数组一致
逻辑说明
- 原矩阵按行优先存储,即原数组索引公式为
row * width + col - 旋转后矩阵的行数等于原矩阵的列数(
width),列数等于原矩阵的行数(height) - 通过反向推导位置映射,确保每个元素都被正确放置到旋转后的位置
内容的提问来源于stack exchange,提问作者tinytree
相关产品推荐
相关产品推荐

