Given a square matrix and we need to write a program to rotate the matrix to the right. Here is the code for the program.
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
#define R 4 | |
#define C 4 | |
void rotateMatrix(int m, int n, int mat[R][C]) { | |
int row = 0, col =0; | |
int curr, prev; | |
while(row<m && col<n) { | |
if(row+1 == m || col+1 == n) | |
break; | |
prev = mat[row+1][col]; | |
for(int i= col; i<n; i++) { | |
curr = mat[row][i]; | |
mat[row][i] = prev; | |
prev = curr; | |
} | |
row++; | |
for(int i=row; i<m; i++) { | |
curr = mat[i][n-1]; | |
mat[i][n-1] = prev; | |
prev = curr; | |
} | |
n--; | |
if(row<m) { | |
for(int i= n-1; i>=col; i--) { | |
curr = mat[m-1][i]; | |
mat[m-1][i] = prev; | |
prev = curr; | |
} | |
} | |
m--; | |
if(col<n){ | |
for(int i=m-1; i>=row; i--) { | |
curr = mat[i][col]; | |
mat[i][col] = prev; | |
prev = curr; | |
} | |
} | |
col++; | |
} | |
for(int i=0; i<R; i++) { | |
for(int j=0; j<C; j++) | |
cout<<mat[i][j]<<" "; | |
cout<<endl; | |
} | |
} | |
int main() { | |
int mat[R][C] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}}; | |
rotateMatrix(R,C,mat); | |
return 0; | |
} |
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
No comments:
Post a Comment