📌  相关文章
📜  C++程序通过顺时针方向将第i行精确旋转i次来修改矩阵

📅  最后修改于: 2022-05-13 01:54:54.849000             🧑  作者: Mango

C++程序通过顺时针方向将第i行精确旋转i次来修改矩阵

给定一个维度为M * N的矩阵mat[][] ,任务是打印矩阵的每第 i行按顺时针方向旋转i次后获得的矩阵。

例子:

解决方法:按照以下步骤解决问题:

  • 以行方式遍历给定的矩阵,并且对于每第 i,执行以下步骤:
    • 反转矩阵的当前行。
    • 反转当前行的前i个元素。
    • 反转当前行的最后(N – i)个元素,其中N是行的当前大小。
  • 完成上述步骤后,打印矩阵mat[][]

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Function to rotate every i-th
// row of the matrix i times
void rotateMatrix(vector >& mat)
{
    int i = 0;
  
    // Traverse the matrix row-wise
    for (auto& it : mat) {
  
        // Reverse the current row
        reverse(it.begin(), it.end());
  
        // Reverse the first i elements
        reverse(it.begin(), it.begin() + i);
  
        // Reverse the last (N - i) elements
        reverse(it.begin() + i, it.end());
  
        // Increment count
        i++;
    }
  
    // Print final matrix
    for (auto rows : mat) {
        for (auto cols : rows) {
            cout << cols << " ";
        }
        cout << "
";
    }
}
  
// Driver Code
int main()
{
    vector > mat
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    rotateMatrix(mat);
  
    return 0;
}


输出:
1 2 3 
6 4 5 
8 9 7

时间复杂度: O(M * N)
辅助空间: O(1)

有关详细信息,请参阅有关通过顺时针方向将第 i 行精确旋转 i 次来修改矩阵的完整文章!