-
Notifications
You must be signed in to change notification settings - Fork 0
/
23_SpiralMatrix.cpp
111 lines (94 loc) · 2.06 KB
/
23_SpiralMatrix.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
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void PrintMatrix(vector<vector<int>> matrix, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
void printVector(vector<int> v){
int n=v.size();
for (int i = 0; i < n; i++)
{
cout<<v[i]<<" ";
}
}
vector<int> spiralPrint(vector<vector<int>> matrix)
{
/*
1 2 3
4 5 6
7 8 9
*/
vector<int> ans;
int row = matrix.size();
int col = matrix[0].size();
int count = 0;
int total = row * col;
// Indexing:
int firstrow = 0;
int firstcol = 0;
int lastrow = row - 1;
int lastcol = col - 1;
while (count < total)
{
// Print first row:
for (int i = firstcol; count < total && i < lastcol; i++)
{
ans.push_back(matrix[firstrow][i]);
count++;
}
firstrow++;
// Print lastcolumn:
for (int i = firstrow; count < total && i < lastrow; i++)
{
ans.push_back(matrix[i][lastcol]);
count++;
}
lastcol--;
// Printing lastrow:
for (int i = lastcol; count < total && i >= firstcol; i--)
{
ans.push_back(matrix[lastrow][i]);
count++;
}
lastrow--;
// Printing firstcol:
for (int i = lastrow; count < total && i >= firstrow; i--)
{
ans.push_back(matrix[i][firstcol]);
count++;
}
firstcol++;
}
return ans;
}
int main()
{
int n;
cout << "enter size of row:";
cin >> n;
vector<vector<int>> v;
cout << "Enter element:" << endl;
for (int i = 0; i < n; i++)
{
vector<int> x;
for (int j = 0; j < n; j++)
{
int value;
cin >> value;
x.push_back(value);
}
v.push_back(x);
}
PrintMatrix(v, n, n);
printVector(spiralPrint(v));
return 0;
}