Skip to content

Commit 82b8189

Browse files
committed
Printing spiral in 2D Matrix
1 parent 0aaaa1d commit 82b8189

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.*;
2+
public class printspiral{
3+
public static void spiral(int matrix[][]){
4+
int startrow=0;
5+
int endrow=matrix.length-1;
6+
int startcol=0;
7+
int endcol=matrix[0].length-1;
8+
while(startrow<=endrow && startcol<=endcol){
9+
//printing Top boundary
10+
for(int j=startcol;j<=endcol;j++){
11+
System.out.println(matrix[startrow][j]+" ");
12+
}
13+
//System.out.println();
14+
//print left extreme
15+
for(int i=startrow+1;i<=endrow;i++){
16+
System.out.println(matrix[i][endcol]+" ");
17+
18+
}
19+
//System.out.println();
20+
//Print bottom boundary
21+
for(int j=endcol-1;j<=startcol;j--){
22+
if(startrow==endrow){
23+
break;
24+
}
25+
System.out.println(matrix[endrow][j]+" ");
26+
}
27+
//System.out.println();
28+
//Print left extreme
29+
for(int i=endrow-1;i<=startrow+1;i--){
30+
if(startcol==endcol){
31+
break;
32+
}
33+
System.out.println(matrix[i][startcol]+" ");
34+
}
35+
//System.out.println();
36+
startrow++;
37+
endrow--;
38+
startcol++;
39+
endcol--;
40+
41+
42+
}
43+
//System.out.println();
44+
45+
}
46+
public static void main(String args[]){
47+
int matrix[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
48+
spiral(matrix);
49+
}
50+
}

0 commit comments

Comments
 (0)