-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathspiral_traversal_2d.cpp
More file actions
85 lines (75 loc) · 1.64 KB
/
spiral_traversal_2d.cpp
File metadata and controls
85 lines (75 loc) · 1.64 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
/*
Spiral Order Matrix Traversal in a 2D Array
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file;
file.open("2d_input.txt");
int n, m;
file >> n;
file >> m;
int arr[n][m];
string line;
getline(file, line);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
file >> arr[i][j];
}
getline(file, line);
}
file.close();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << endl
<< endl;
int start_row = 0;
int start_column = 0;
int end_row = n - 1;
int end_column = m - 1;
while (start_row <= end_row && start_column <= end_column)
{
for (int i = start_column; i <= end_column; i++)
{
cout << arr[start_row][i] << " ";
}
cout << endl;
start_row++;
for (int i = start_row; i <= end_row; i++)
{
cout << arr[i][end_column] << " ";
}
cout << endl;
end_column--;
if(start_row<=end_row)
{
for (int i = end_column; i >= start_column; i--)
{
cout << arr[end_row][i] << " ";
}
cout << endl;
}
end_row--;
if (start_column <= end_column)
{
for (int i = end_row; i >= start_row; i--)
{
cout << arr[i][start_column] << " ";
}
cout << endl;
}
start_column++;
}
return 0;
}