亚麻:Rotate Matrix

这是亚麻的OA 题

带补充。。。。

// C++ program to rotate a matrix by 90 degrees

#define N 4
#include <stdio.h>
using namespace std;

void displayMatrix(int mat[N][N]);

// An Inplace function to rotate a N x N matrix
// by 90 degrees in anti-clockwise direction
void rotateMatrix(int mat[][N])
{
    // Consider all squares one by one
    for (int x = 0; x < N / 2; x++)
    {
        // Consider elements in group of 4 in
        // current square
        for (int y = x; y < N-x-1; y++)
        {
            // store current cell in temp variable
            int temp = mat[x][y];
            
            // move values from right to top
            mat[x][y] = mat[y][N-1-x];
            
            // move values from bottom to right
            mat[y][N-1-x] = mat[N-1-x][N-1-y];
            
            // move values from left to bottom
            mat[N-1-x][N-1-y] = mat[N-1-y][x];
            
            // assign temp to left
            mat[N-1-y][x] = temp;
        }
    }
}

// Function to print the matrix
void displayMatrix(int mat[N][N])
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            printf("%2d ", mat[i][j]);
        
        printf("\n");
    }
    printf("\n");
}


/* Driver program to test above functions */
int main()
{
    // Test Case 1
    int mat[N][N] =
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    
    
    // Tese Case 2
    /* int mat[N][N] = {
     {1, 2, 3},
     {4, 5, 6},
     {7, 8, 9}
     };
     */
    
    // Tese Case 3
    /*int mat[N][N] = {
     {1, 2},
     {4, 5}
     };*/
    
    //displayMatrix(mat);
    
    rotateMatrix(mat);
    
    // Print rotated matrix
    displayMatrix(mat);
    
    return 0;
}

 

转载于:https://www.cnblogs.com/HisonSanDiego/p/8283444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值