-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintSpiral.java
81 lines (71 loc) · 1.7 KB
/
PrintSpiral.java
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*Print Spiral
For a given two-dimensional integer array/list of size (N x M), print it in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right) b. Last column(top to bottom)
c. Last row(right to left) d. First column(bottom to top)*/
import java.util.Scanner;
public class PrintSpiral
{
public static void PrintSpiral(int arr[][])
{
if (arr.length == 0)
{
return;
}
int row = arr.length;
int col = arr[0].length;
if (arr.length == 0){return ;}
int k=1;
int r1=0,r2=row-1;
int c1=0,c2=col-1;
while(k<=row*col)
{
for(int i=c1;i<=c2;i++)
{
System.out.print(arr[r1][i] + " ");
k++;
}
r1++;
for(int i=r1;i<=r2;i++)
{
System.out.print(arr[i][c2] + " ");
k++;
}
c2--;
for(int i=c2;i>=c1;i--)
{
System.out.print(arr[r2][i] + " ");
k++;
}
r2--;
for(int i=r2;i>=r1;i--)
{
System.out.print(arr[i][c1] + " ");
k++;
}
c1++;
}
}
public static int[][] takeInput()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the row size");
int rows=s.nextInt();
System.out.println("Enter the column size");
int cols=s.nextInt();
int[][] arr=new int[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.println("Enter the element at "+ i+ "th row and "+j+"th column");
arr[i][j]=s.nextInt();
}
}
return arr;
}
public static void main(String args[])
{
int [][]input=takeInput();
PrintSpiral(input);
}
}