-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral traversal
62 lines (50 loc) · 1.4 KB
/
spiral traversal
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scn=new Scanner(System.in);
int row=scn.nextInt();
int col=scn.nextInt();
int[][] arr=new int[row][col];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
arr[i][j]=scn.nextInt();
}
}
int minrow=0;
int mincol=0;
int maxrow=row-1;
int maxcol=col-1;
int te=row*col;
int count=0;
while(count<te)
{
for(int i=minrow,j=mincol;i<=maxrow && count<te;i++)
{
System.out.println(arr[i][j]);
count++;
}
mincol++;
for(int i=maxrow,j=mincol;j<=maxcol && count<te;j++)
{
System.out.println(arr[i][j]);
count++;
}
maxrow--;
for(int i=maxrow,j=maxcol;i>=minrow && count<te;i--)
{
System.out.println(arr[i][j]);
count++;
}
maxcol--;
for(int i=minrow,j=maxcol;j>=mincol && count<te;j--)
{
System.out.println(arr[i][j]);
count++;
}
minrow++;
}
}
}