-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
54 lines (45 loc) · 1.01 KB
/
SpiralMatrix.java
File metadata and controls
54 lines (45 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Spiral Matrix
// Time complexity O(mn)
import java.util.*;
public class SpiralMatrix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Size(m*n) of 2D matrix: ");
int m=sc.nextInt();
int n=sc.nextInt();
System.out.println("Enter the Matrix Element: ");
int a[][]=new int[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=sc.nextInt();
int i,top=0,left=0,down=m,right=n;
System.out.println("Spiral matrix: ");
while(top<=down && left<=right)
{
// first Row
for(i=left;i<right;i++)
System.out.print(" "+a[top][i]+" ");
top++;
// last column
for(i=top;i<down;i++)
System.out.print(" "+a[i][right-1]+" ");
right--;
// last row
if(top<down)
{
for(i=right-1;i>=left;--i)
System.out.print(" "+a[down-1][i]+" ");
down--;
}
// first column
if(left<right)
{
for(i=down-1;i>=top;--i)
System.out.print(" "+a[i][left]+" ");
}
left++;
}
}
}