Skip to content

Commit 1eaefc6

Browse files
authored
Merge pull request ashutosh97#86 from Akshayy99/new-branch
Added spiralMatrix problem for C++
2 parents b0244c7 + 1f98301 commit 1eaefc6

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

SpiralMatrix/problem.txt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Given a 2D array, print it in spiral form. See the following examples.
2+
3+
Examples:
4+
5+
Input:
6+
1 2 3 4
7+
5 6 7 8
8+
9 10 11 12
9+
13 14 15 16
10+
11+
Output:
12+
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
13+
14+
15+
Input:
16+
1 2 3 4 5 6
17+
7 8 9 10 11 12
18+
13 14 15 16 17 18
19+
20+
Output:
21+
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11

SpiralMatrix/solution.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
#define R 3
4+
#define C 6
5+
6+
void spiralPrint(int m, int n, int a[R][C])
7+
{
8+
int i, k = 0, l = 0;
9+
10+
while (k < m && l < n)
11+
{
12+
for (i = l; i < n; ++i)
13+
cout << a[k][i] << " ";
14+
k++;
15+
16+
for (i = k; i < m; ++i)
17+
cout << a[i][n - 1] << " ";
18+
n--;
19+
20+
if (k < m)
21+
{
22+
for (i = n - 1; i >= l; --i)
23+
cout << a[m - 1][i] << " ";
24+
m--;
25+
}
26+
27+
if (l < n) {
28+
for (i = m - 1; i >= k; --i)
29+
cout << a[i][l] << " ";
30+
l++;
31+
}
32+
}
33+
}
34+
35+
int main()
36+
{
37+
int a[R][C] = { { 1, 2, 3, 4, 5, 6 },
38+
{ 7, 8, 9, 10, 11, 12 },
39+
{ 13, 14, 15, 16, 17, 18 } };
40+
41+
spiralPrint(R, C, a);
42+
return 0;
43+
}

0 commit comments

Comments
 (0)