forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate2darray.cpp
118 lines (110 loc) · 2.15 KB
/
rotate2darray.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
This code is for Rotating an NxN 2D array in 90 degrees anticlockwise direction.
*/
#include <bits/stdc++.h>
using namespace std;
//function to rotate the user matrix anticlockwise
void rotatematrix(int a[][10], int n)
{
//reversing each row
for (int row = 0; row < n; row++)
{
int start_col = 0;
int end_col = n - 1;
while (start_col < end_col)
{
swap(a[row][start_col], a[row][end_col]);
start_col++;
end_col--;
}
}
//taking transpose
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i < j)
{
swap(a[i][j], a[j][i]);
}
}
}
}
//function for displaying the rotated 2darray/matrix
void display(int a[10][10], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j]<<" ";
}
cout<<endl;
}
}
//driver function
int main()
{
int a[10][10];
//'n' here is declared for the order of your matrix
int n;
//taking input for the order of matrix
cout << "enter the order for your square matrix:" << endl;
cin >> n;
//taking input for the matrix data
cout << "please enter the elements of your matrix to be Rotated:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
cout << "the matrix to be rotated:" << endl;
//calling the function for displaying the initial matrix
display(a, n);
//calling the function for rotating the matrix
rotatematrix(a, n);
cout << "the matrix after rotation:" << endl;
//calling the function for displaying the rotated matrix
display(a, n);
}
/*EXECUTION:-
SAMPLE OUTPUT-1:
enter the order for your square matrix:
2
please enter the elements of your matrix to be Rotated:
1
2
3
4
the matrix to be rotated:
1 2
3 4
the matrix after rotation:
2 4
1 3
SAMPLE OUTPUT-2:
enter the order for your square matrix:
3
please enter the elements of your matrix to be Rotated:
2
3
4
5
6
7
8
9
1
the matrix to be rotated:
2 3 4
5 6 7
8 9 1
the matrix after rotation:
4 7 1
3 6 9
2 5 8
The time complexity of the code is O(N2) for an N × N matrix
and it doesn’t require any extra space therefore the space complexity is O(1).
*/