forked from Knackie/algorithmshacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpiralMatrix.java
50 lines (42 loc) · 967 Bytes
/
SpiralMatrix.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
import java.util.*;
class SpiralMatrix{
// Function to print in spiral order
public static List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> ans = new ArrayList<Integer>();
if (matrix.length == 0)
return ans;
int R = matrix.length, C = matrix[0].length;
boolean[][] seen = new boolean[R][C];
int[] dr = { 0, 1, 0, -1 };
int[] dc = { 1, 0, -1, 0 };
int r = 0, c = 0, di = 0;
// Iterate from 0 to R * C - 1
for (int i = 0; i < R * C; i++) {
ans.add(matrix[r]);
seen[r] = true;
int cr = r + dr[di];
int cc = c + dc[di];
if (0 <= cr && cr < R && 0 <= cc && cc < C
&& !seen[cr][cc]) {
r = cr;
c = cc;
}
else {
di = (di + 1) % 4;
r += dr[di];
c += dc[di];
}
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
System.out.println(spiralOrder(a));
}
}