栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

旋转M * N矩阵(90度)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

旋转M * N矩阵(90度)

如果矩阵是由array表示的

matrix[i, j]
,其中的
i
是行,而的
j
是列,则请实施以下方法:

static int[,] RotateMatrixCounterClockwise(int[,] oldMatrix){    int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];    int newColumn, newRow = 0;    for (int oldColumn = oldMatrix.GetLength(1) - 1; oldColumn >= 0; oldColumn--)    {        newColumn = 0;        for (int oldRow = 0; oldRow < oldMatrix.GetLength(0); oldRow++)        { newMatrix[newRow, newColumn] = oldMatrix[oldRow, oldColumn]; newColumn++;        }        newRow++;    }    return newMatrix;}

这适用于所有大小的矩阵。

编辑 :如果此操作太昂贵,则可以尝试更改 读取 矩阵的方式,而不是更改矩阵 本身 。例如,如果我按如下所示显示矩阵:

for (int row = 0; row < matrix.GetLength(0); row++){    for (int col = 0; col < matrix.GetLength(1); col++)    {        Console.Write(matrix[row, col] + " ");    }    Console.WriteLine();}

那么我可以通过更改读取矩阵的方式来表示逆时针旋转90度:

for (int col = matrix.GetLength(1) - 1; col >= 0; col--){    for (int row = 0; row < matrix.GetLength(0); row++)    {        Console.Write(matrix[row, col] + " ");    }    Console.WriteLine();}

该访问模式也可以抽象为一个类。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624018.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号