- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathPrintAMatrixInSpiralOrder.java
52 lines (50 loc) · 1.69 KB
/
PrintAMatrixInSpiralOrder.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
packagecom.thealgorithms.others;
importjava.util.ArrayList;
importjava.util.List;
publicclassPrintAMatrixInSpiralOrder {
/**
* Search a key in row and column wise sorted matrix
*
* @param matrix matrix to be searched
* @param row number of rows matrix has
* @param col number of columns matrix has
* @author Sadiul Hakim : https://github.com/sadiul-hakim
*/
publicList<Integer> print(int[][] matrix, introw, intcol) {
// r traverses matrix row wise from first
intr = 0;
// c traverses matrix column wise from first
intc = 0;
inti;
List<Integer> result = newArrayList<>();
while (r < row && c < col) {
// print first row of matrix
for (i = c; i < col; i++) {
result.add(matrix[r][i]);
}
// increase r by one because first row printed
r++;
// print last column
for (i = r; i < row; i++) {
result.add(matrix[i][col - 1]);
}
// decrease col by one because last column has been printed
col--;
// print rows from last except printed elements
if (r < row) {
for (i = col - 1; i >= c; i--) {
result.add(matrix[row - 1][i]);
}
row--;
}
// print columns from first except printed elements
if (c < col) {
for (i = row - 1; i >= r; i--) {
result.add(matrix[i][c]);
}
c++;
}
}
returnresult;
}
}