-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23_spiralPrint.cpp
108 lines (95 loc) · 2.48 KB
/
23_spiralPrint.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
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;
}
}
// Function to return a list of integers denoting spiral traversal of matrix.
vector<int> spirallyTraverse(vector<vector<int>> matrix, int r, int c)
{
// code here
vector<int> ans;
int row = r;
int col = c;
int total = row * col;
int count = 0;
// Indexing:
int firstrow = 0;
int firstcol = 0;
int lastrow = row - 1;
int lastcol = col - 1;
while (count < total)
{
// printing firstrow:
for (int i = firstcol; count < total && i <= lastcol; i++)
{
ans.push_back(matrix[firstrow][i]);
count++;
}
firstrow++;
// Last column:
for (int i = firstrow; count < total && i <= lastrow; i++)
{
ans.push_back(matrix[i][lastcol]);
count++;
}
lastcol--;
// lastrow:
for (int i = lastcol; count < total && i >= firstcol; i--)
{
ans.push_back(matrix[lastrow][i]);
count++;
}
lastrow--;
// First column
for (int i = lastrow; count < total && i >= firstrow; i--)
{
ans.push_back(matrix[i][firstcol]);
count++;
}
firstcol++;
}
return ans;
}
};
//{ Driver Code Starts.
int main()
{
int r, c;
cout << "enter row:";
cin >> r;
cout << "enter col:";
cin >> c;
vector<vector<int>> matrix(r);
cout << "enter the elements of matrix:" << endl;
for (int i = 0; i < r; i++)
{
matrix[i].assign(c, 0);
for (int j = 0; j < c; j++)
{
cin >> matrix[i][j];
}
}
Solution ob;
cout << "matrix:" << endl;
ob.PrintMatrix(matrix, r, c);
cout << "spiral Print:" << endl;
vector<int> result = ob.spirallyTraverse(matrix, r, c);
for (int i = 0; i < result.size(); ++i)
cout << result[i] << " ";
cout << endl;
return 0;
}
// } Driver Code Ends