Rotate the matrix right by K times — Solution

Soumyadeep Pradhan
2 min readJun 24, 2021

Problem Statement — Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side.

Input :  N = 3, M = 3, K = 2
12 23 34
45 56 67
78 89 91

Output : 23 34 12
56 67 45
89 91 78

Input : N = 2, M = 2, K = 2
1 2
3 4

Output : 1 2
3 4

Solution-

#include <iostream>

#define M 3
#define N 3

using namespace std;

void rotateMatrix(int matrix[][M], int k) {
int temp[M];

k = k % M;

for (int i = 0; i < N; i++) {
for (int t = 0; t < M — k; t++)
temp[t] = matrix[i][t];

for (int j = M — k; j < M; j++)
matrix[i][j — M + k] = matrix[i][j];

for (int j = k; j < M; j++)
matrix[i][j] = temp[j — k];
}
}

void displayMatrix(int matrix[][M]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
cout << matrix[i][j] << “ “;
cout << endl;
}
}

int main() {
int matrix[N][M] = {{12, 23, 34},
{45, 56, 67},
{78, 89, 91}};
int k = 2;

rotateMatrix(matrix, k);

displayMatrix(matrix);

return 0;
}

--

--