-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Rotate a matrix by 90 degree without using any extra space
- Loading branch information
1 parent
4cf3629
commit 8304a77
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
57 changes: 57 additions & 0 deletions
57
Rotate a matrix by 90 degree without using any extra space
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// C++ program for left | ||
// rotation of matrix by 90 degree | ||
// without using extra space | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
#define R 4 | ||
#define C 4 | ||
|
||
// After transpose we swap | ||
// elements of column | ||
// one by one for finding left | ||
// rotation of matrix | ||
// by 90 degree | ||
void reverseColumns(int arr[R][C]) | ||
{ | ||
for (int i = 0; i < C; i++) | ||
for (int j = 0, k = C - 1; j < k; j++, k--) | ||
swap(arr[j][i], arr[k][i]); | ||
} | ||
|
||
// Function for do transpose of matrix | ||
void transpose(int arr[R][C]) | ||
{ | ||
for (int i = 0; i < R; i++) | ||
for (int j = i; j < C; j++) | ||
swap(arr[i][j], arr[j][i]); | ||
} | ||
|
||
// Function for print matrix | ||
void printMatrix(int arr[R][C]) | ||
{ | ||
for (int i = 0; i < R; i++) { | ||
for (int j = 0; j < C; j++) | ||
cout << arr[i][j] << " "; | ||
cout << '\n'; | ||
} | ||
} | ||
|
||
// Function to anticlockwise | ||
// rotate matrix by 90 degree | ||
void rotate90(int arr[R][C]) | ||
{ | ||
transpose(arr); | ||
reverseColumns(arr); | ||
} | ||
|
||
// Driven code | ||
int main() | ||
{ | ||
int arr[R][C] = { { 1, 2, 3, 4 }, | ||
{ 5, 6, 7, 8 }, | ||
{ 9, 10, 11, 12 }, | ||
{ 13, 14, 15, 16 } }; | ||
rotate90(arr); | ||
printMatrix(arr); | ||
return 0; | ||
} |