forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiralMatrix.java
More file actions
57 lines (50 loc) · 1.29 KB
/
spiralMatrix.java
File metadata and controls
57 lines (50 loc) · 1.29 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
55
56
57
import java.util.*;
public class spiralMatrix {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = s.nextInt();
spiral(arr, n, m);
}
static void spiral(int[][] arr, int n, int m) {
int top=0;
int left=0;
int right=arr[0].length-1;
int bottom=arr.length-1;
while(left<=right)
{
for(int i=left;i<=right;i++)
{
System.out.print(arr[top][i]+" ");
}
top++;
if(top>bottom)
{
break;
}
for(int i=top;i<=bottom;i++)
{
System.out.print(arr[i][right]+" ");
}
right--;
for(int i=right;i>=left;i--)
{
System.out.print(arr[bottom][i]+" ");
}
bottom--;
if(top>bottom)
{
break;
}
for(int i=bottom;i>=top;i--)
{
System.out.print(arr[i][left]+" ");
}
left++;
}
}
}