-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathSpiralMatrixSort.cpp
131 lines (111 loc) · 2.12 KB
/
SpiralMatrixSort.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
119
120
121
122
123
124
125
126
127
128
129
130
131
// C++ program to Convert given Matrix
// into sorted Spiral Matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
// Function to convert the array to Spiral
void ToSpiral(int m, int n,
int Sorted[], int a[MAX][MAX])
{
// For Array pointer
int index = 0;
// k - starting row index
// m - ending row index
// l - starting column index
// n - ending column index
int k = 0, l = 0;
while (k < m && l < n)
{
// Print the first row
// from the remaining rows
for (int i = l; i < n; ++i)
{
a[k][i] = Sorted[index];
index++;
}
k++;
// Print the last column
// from the remaining columns
for (int i = k; i < m; ++i)
{
a[i][n - 1] = Sorted[index];
index++;
}
n--;
// Print the last row
// from the remaining rows
if (k < m)
{
for (int i = n - 1; i >= l; --i)
{
a[m - 1][i] = Sorted[index];
index++;
}
m--;
}
// Print the first column
// from the remaining columns
if (l < n)
{
for (int i = m - 1; i >= k; --i)
{
a[i][l] = Sorted[index];
index++;
}
l++;
}
}
}
// Function to convert 2D array to 1D array
void convert2Dto1D(int y[MAX][MAX],
int m, int n,int x[])
{
int index = 0;
// Store value 2D Matrix To 1D array
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
x[index] = y[i][j];
index++;
}
}
}
// Function to print the Matrix
void PrintMatrix(int a[MAX][MAX],
int m, int n)
{
// Print Spiral Matrix
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
// Function to Convert given Matrix
// into sorted Spiral Matrix
void convertMatrixToSortedSpiral(
int y[MAX][MAX], int m, int n)
{
int a[MAX][MAX] = {0};
int x[m * n];
convert2Dto1D(y, m, n,x);
sort(x, x + n * m);
ToSpiral(m, n, x, a);
PrintMatrix(a, m, n);
}
// Driver code
int main()
{
int m = 4, n = 3;
int y[MAX][MAX] = {
{ 2, 5, 12 },
{ 22, 45, 55 },
{ 1, 6, 8 },
{ 13, 56, 10 }};
convertMatrixToSortedSpiral(y, m, n);
return 0;
}