Skip to content

Commit 562dca8

Browse files
committed
Spiral Traversal
1 parent df190c9 commit 562dca8

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Matrix/SpiralTraversal.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package SummerTrainingGFG.Matrix;
2+
/**
3+
* @author Vishal Singh */
4+
public class SpiralTraversal {
5+
static void spiralTraversal(int[][] arr,int row,int column){
6+
int top = 0;
7+
int left = 0;
8+
int right = row-1;
9+
int bottom = column-1;
10+
while (top <= bottom && left <= right){
11+
for (int i = top; i <=right ; i++) {
12+
System.out.print(arr[top][i]+" ");
13+
}
14+
top++;
15+
for (int i = top; i <=bottom ; i++) {
16+
System.out.print(arr[i][right]+" ");
17+
}
18+
right--;
19+
if (top<=bottom){
20+
for (int i = right; i >= left; i--) {
21+
System.out.print(arr[bottom][i]+" ");
22+
}
23+
bottom--;
24+
}
25+
if (left<=right){
26+
for (int i = bottom; i >= top; i--) {
27+
System.out.print(arr[i][left]+" ");
28+
}
29+
left++;
30+
}
31+
}
32+
}
33+
public static void main(String[] args) {
34+
int[][] arr = {
35+
{1,2,3,4},
36+
{5,6,7,8},
37+
{9,10,11,12},
38+
{13,14,15,16},
39+
};
40+
spiralTraversal(arr,4,4);
41+
}
42+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ Java Solution for Data Structures and Algorithms.
109109
<b>10. [MATRIX](Matrix)</b>
110110

111111
* [Snake Pattern](Matrix/SnakePattern.java)
112+
* [Spiral Traversal](Matrix/SpiralTraversal.java)
112113

113114
### `NOTE: Raise an issue if any program doesn't work.`
114115
### `More Topics to be added soon`

0 commit comments

Comments
 (0)