-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathspiralMatrix.cpp
60 lines (53 loc) · 1.31 KB
/
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
#include <bits/stdc++.h>
using namespace std;
void spiralMatrix(int arr[][3])
{
int row = 3;
int col = 3;
int count = 0;
int total = row * col;
int startRow = 0;
int endRow = row - 1;
int startCol = 0;
int endCol = col - 1;
while (count < total)
{
// printing starting row
for (int index = startCol; index <= endCol && count < total; index++)
{
cout << arr[startRow][index];
count++;
}
startRow++;
// printing ending column
for (int index = startRow; index <= endRow && count < total; index++)
{
cout << arr[index][endCol];
count++;
}
endCol--;
// printing ending row
for (int index = endCol; index >= startCol && count < total; index--)
{
cout << arr[endRow][index];
count++;
}
endRow--;
// printing starting column
for (int index = endRow; index >= startRow && count < total; index--)
{
cout << arr[index][startCol];
count++;
}
startCol++;
}
}
int main()
{
int arr[3][3];
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
cin >> arr[row][col];
spiralMatrix(arr);
return 0;
}