-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclockwise_spiral.cpp
More file actions
86 lines (75 loc) · 2.13 KB
/
clockwise_spiral.cpp
File metadata and controls
86 lines (75 loc) · 2.13 KB
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
//
// Created by Mayank Parasar on 2019-12-17.
//
/*
* You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix.
*
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int>& clockwise_spiral(vector<vector<int>>& a, vector<int>& clockwise_sprial_1) {
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/
int m = a.size();
int n = a[0].size();
while (k < m && l < n) {
/* Print the first row from
the remaining rows */
for (i = l; i < n; ++i) {
// cout << a[k][i] << " ";
clockwise_sprial_1.push_back(a[k][i]);
}
k++;
/* Print the last column
from the remaining columns */
for (i = k; i < m; ++i) {
// cout << a[i][n - 1] << " ";
clockwise_sprial_1.push_back(a[i][n - 1]);
}
n--;
/* Print the last row from
the remaining rows */
if (k < m) {
for (i = n - 1; i >= l; --i) {
// cout << a[m - 1][i] << " ";
clockwise_sprial_1.push_back(a[m - 1][i]);
}
m--;
}
/* Print the first column from
the remaining columns */
if (l < n) {
for (i = m - 1; i >= k; --i) {
// cout << a[i][l] << " ";
clockwise_sprial_1.push_back(a[i][l]);
}
l++;
}
}
return(clockwise_sprial_1);
}
int main() {
// Initializing 2D vector "vect" with
// values
vector<vector<int> > vect{ { 1, 2, 3, 10 },
{ 4, 5, 6, 11 },
{ 7, 8, 9, 12 } };
for(int i = 0; i < vect.size(); i++) {
for(int k = 0; k < vect[i].size(); k++) {
cout << vect[i][k] <<" ";
}
cout << endl;
}
vector<int> clockwise_spiral_1;
clockwise_spiral(vect, clockwise_spiral_1);
for(auto i: clockwise_spiral_1) {
cout << i << " ";
}
return 0;
}