-
Notifications
You must be signed in to change notification settings - Fork 804
/
update matrix in spiral form in c++
52 lines (41 loc) · 1.11 KB
/
update matrix in spiral form in c++
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
#include <bits/stdc++.h>
#define r 4
#define c 4
using namespace std;
int main()
{
int a[4][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int i, left = 0, right = c-1, top = 0, bottom = r-1;
while (left <= right && top <= bottom) {
/* Print the first row
from the remaining rows */
for (i = left; i <= right; ++i) {
cout<<a[top][i]<<" ";
}
top++;
/* Print the last column
from the remaining columns */
for (i = top; i <= bottom; ++i) {
cout<<a[i][right]<<" ";
}
right--;
/* Print the last row from
the remaining rows */
if (top <= bottom) { for (i = right; i >= left; --i) {
cout<<a[bottom][i]<<" ";
}
bottom--;
}
/* Print the first column from
the remaining columns */
if (left <= right) { for (i = bottom; i >= top; --i) {
cout<<a[i][left]<<" ";
}
left++;
}
}
return 0;
}