Spiral Print
For a given two-dimensional integer array/list of size (N x M), print it in a spiral form. That is, you need to print in the order followed for every iteration:
Mind that every element will be printed only once.
Refer to the Image:

Input format :
Output format :
Constraints :
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
#include <iostream>
using namespace std;
#include "solution.h"
void spiralPrint(int **input, int m, int n)
{
//Write your code here
int rowstart=0;
int rowend=m-1;
int colstart=0;
int colend=n-1;
int elements=(m*n);
while(elements>0){
for(int i=rowstart;i<=colend;i++){
cout<<input[rowstart][i]<<" ";
elements--;
}
rowstart=rowstart+1;
for(int i=rowstart;i<=rowend;i++){
cout<<input[i][colend]<<" ";
elements--;
}
colend=colend-1;
for(int i=colend;i>=colstart;i--){
cout<<input[rowend][i]<<" ";
elements--;
}
rowend=rowend-1;
for(int i=rowend;i>=rowstart;i--){
cout<<input[i][colstart]<<" ";
elements--;
}
colstart=colstart+1;
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
int row, col;
cin >> row >> col;
int **matrix = new int *[row];
for (int i = 0; i < row; i++)
{
matrix[i] = new int[col];
for (int j = 0; j < col; j++)
{
cin >> matrix[i][j];
}
}
spiralPrint(matrix, row, col);
for (int i = 0; i < row; ++i)
{
delete[] matrix[i];
}
delete[] matrix;
cout << endl;
}
}
Comments
Post a Comment