Q) Take as input a 2-d array. Print the 2-D array in spiral form anti-clockwise.
Input Format
Two integers M(row) and N(column) and further M * N integers(2-d array numbers).
Constraints
Both M and N are between 1 to 10.
Output Format
All M * N integers separated by commas with ‘END’ written in the end(as shown in example).
Sample Input
4 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
Sample Output
11, 21, 31, 41, 42, 43, 44, 34, 24, 14, 13, 12, 22, 32, 33, 23, END
Explanation
For spiral level anti-clockwise traversal, Go for first column-> last row ->last column-> first row and then do the same traversal for the remaining matrix .
Code Implemented by me :-
#include
using namespace std;
void spiral_print (int a[][1000] , int m, int n ) // need array, row and column
{
int startRow = 0;
int startCol = 0;
int endRow = m-1;
int endCol = n-1;
while (startRow <= endRow && startCol <= endCol)
{
// Print the First Column
for (int i = startRow; i <= endRow; i++)
{
cout << a[i][startCol] << ", ";
}
startCol ++ ; // for next iteration... we have updated the columns
// now print the last row
for (int i = startCol; i <= endCol; i++)
{
cout << a[endRow][i] << ", ";
}
endRow-- ;
// now print the last column
if (endCol > startCol) // this condition for all MATRIX
{
for (int i = endRow; i >= startRow; i--)
{
cout << a[i][endCol] << ", ";
}
endCol-- ;
// now print the first row
}
if (endRow > startRow) // this condition for all MATRIX
{
for (int i = endCol; i >= startCol; i--)
{
cout << a[startRow][i] << ", ";
}
startRow++;
}
}
}
int main()
{
int a[1000][1000];
int m,n;
// cout << "Enter the number of rows : ";
cin >> m;
// cout << "Enter the number of columns : ";
cin >> n;
for (int row = 0; row <=m-1; row++)
{
for (int col = 0; col <=n-1; col++)
{
cin >> a[row][col];
}
cout << endl;
}
cout << endl;
spiral_print (a,m,n);
cout <<"END";
return 0;
}
The above code is working upto some extent but some TEST CASES are not working with it.
Can you please figure out the problem in my above code and update my code.
Else, provide me the code for the above Question.
Thank you