Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form . This article discusses how to do the reverse printing. See the following examples.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Javascript
<script>
let R = 3;
let C = 6;
function ReversespiralPrint(m, n, a)
{
let b = new Array(100);
let i, k = 0, l = 0;
let z = 0;
let size = m*n;
while (k < m && l < n)
{
let val;
for (i = l; i < n; ++i)
{
val = a[k][i];
b[z] = val;
++z;
}
k++;
for (i = k; i < m; ++i)
{
val = a[i][n-1];
b[z] = val;
++z;
}
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
val = a[m-1][i];
b[z] = val;
++z;
}
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
{
val = a[i][l];
b[z] = val;
++z;
}
l++;
}
}
for (let i=size-1 ; i>=0 ; --i)
{
document.write(b[i] + " ");
}
}
let a = [ [1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]];
ReversespiralPrint(R, C, a);
</script>
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Time complexity: O(R*C) where R and C are no of rows and columns in given matrix
Auxiliary Space : O(1) because using constant space
Please refer complete article on Print a given matrix in reverse spiral form for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule. Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
15 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...