Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to print a given matrix in spiral form.

Write a program to print a given matrix in spiral form.

Given a matrix we have to print matrix in spiral form and print the resultant matrix in spiral form.

Example:

Input:1 2 3 4 5 6
Output:1 2 3 6 5 4 

Logic:

STEP 1:  idea is to just traverse whole array.
STEP 2: initalise variable left,right,row,col.
STEP 3:start  traversing form left to right ,then top to bottom.

Code

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int row,col;
    cin>>row>>col;
    int a[row][col];
    for(int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cin>>a[i][j];
        }
    }
    int i=0;
int left=0;
int right =0;
	while (left< row && right < col)
	{
	
		for (i = right; i < col; ++i) {
			cout<<a[left][i] << " ";
		}
		left++;

	
		for (i = left; i < row; ++i) {
			cout<<a[i][col - 1]<<" ";
		}
		col--;

	
		if (left < row) {
			for (i = row - 1; i >= right; --i) {
				cout << a[row - 1][i]<<" ";
			}
			row--;
		}

	
		if (right< row) {
			for (i = row - 1; i >= left; --i) {
				cout << a[i][right]<<" ";
			}
			right++;
		}
	}




}

Ouput:

1 2 3 6 5 4 

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments