Sitemap
Ashmeet Kaur

Ashmeet Kaur

Writing articles on core Java Development .

Spiral Matrix

2 min readJan 5, 2023

There given a 2D matrix . You need to find the matrix in the spiral order.

This above matrix is of form nxm.(3x5).

Get Ashmeet Kaur’s stories in your inbox

Join Medium for free to get updates from this writer.

Output-
11 21 31 32 33 34 35 25 15 14 13 12 11
Lets understand this
I).During the first iteration, We are suppose to print left side ,down side,
right side ,up side .

Here printing 11 21 31 32 34 35 25 15 14 13 12 11 in the spiral way.
So we have to print every rectangle inside the rectangle .
But there can come a point where there might be single line or a single element.

22 23 24
So after every line , We have to check whether the element is completed or not . or other wise it will prevent the reverse also .
Lets jump to the code here

import java.io.*;
import java.util.*;

public class Main {

public static void main(String[] args) throws Exception
{
int row=0;
int col=0;
int i=0;
int j=0;
Scanner sc=new Scanner(System.in);
row=sc.nextInt();
col=sc.nextInt();
int [][]arr=new int[row][col];
for(i=0;i<row;++i)
{
for(j=0;j<col;++j)
{
arr[i][j]=sc.nextInt();
}
}




int current_col=0;
int current_row=0;
int count=0;
int k=0;
int total_elements=row*col;

while(count<=total_elements)
{
for(i=k;i<row-k;++i)
{
++count;
System.out.println(arr[i][current_col]);


}
if(count==total_elements)
{
break;
}
current_row=i-1;
current_col=current_col+1;
for(j=current_col;j<col-k;++j)
{
++count;
System.out.println(arr[current_row][j]);

}
if(count==total_elements)
{
break;
}
current_col=j-1;
current_row=current_row-1;
for(i=current_row;i>=k;--i)
{
++count;
System.out.println(arr[i][current_col]);



}
if(count==total_elements)
{
break;
}
current_row=i+1;
current_col=current_col-1;
for(j=current_col;j>k;--j)
{
++count;
System.out.println(arr[current_row][j]);


}
if(count==total_elements)
{
break;
}
current_col=k+1;
current_row=k+1;
++k;


}



}

}

So this will take O(n²).

Please find the leetcode solution .
https://leetcode.com/problems/spiral-matrix/submissions/872082344/

--

--

Ashmeet Kaur
Ashmeet Kaur

Written by Ashmeet Kaur

Writing articles on core Java Development .