Skip to content

Commit 7a5102c

Browse files
authored
Update PrintAMatrixInSpiralOrder.java
1 parent fc4d76d commit 7a5102c

File tree

1 file changed

+19
-28
lines changed

1 file changed

+19
-28
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.thealgorithms.others;
22

3+
import java.util.ArrayList;
4+
import java.util.List;
5+
36
public class PrintAMatrixInSpiralOrder {
47
/**
58
* Search a key in row and column wise sorted matrix
@@ -10,65 +13,53 @@ public class PrintAMatrixInSpiralOrder {
1013
* @author Sadiul Hakim : https://github.com/sadiul-hakim
1114
*/
1215

13-
public void print(int[][] matrix, int row, int col) {
16+
public List<Integer> print(int[][] matrix, int row, int col) {
1417

15-
//r traverses matrix row wise from first
18+
// r traverses matrix row wise from first
1619
int r = 0;
17-
//c traverses matrix column wise from first
20+
// c traverses matrix column wise from first
1821
int c = 0;
1922
int i;
2023

24+
List<Integer> result = new ArrayList<>();
25+
2126
while (r < row && c < col) {
22-
//print first row of matrix
27+
// print first row of matrix
2328
for (i = c; i < col; i++) {
24-
System.out.print(matrix[r][i] + " ");
25-
29+
result.add(matrix[r][i]);
2630
}
2731

28-
//increase r by one because first row printed
32+
// increase r by one because first row printed
2933
r++;
3034

31-
//print last column
35+
// print last column
3236
for (i = r; i < row; i++) {
33-
System.out.print(matrix[i][col - 1] + " ");
37+
result.add(matrix[i][col - 1]);
3438
}
3539

36-
//decrease col by one because last column has been printed
40+
// decrease col by one because last column has been printed
3741
col--;
3842

39-
//print rows from last except printed elements
43+
// print rows from last except printed elements
4044
if (r < row) {
4145
for (i = col - 1; i >= c; i--) {
42-
System.out.print(matrix[row - 1][i] + " ");
46+
result.add(matrix[row - 1][i]);
4347
}
4448

4549
row--;
4650

4751
}
4852

49-
//print columns from first except printed elements
53+
// print columns from first except printed elements
5054
if (c < col) {
5155
for (i = row - 1; i >= r; i--) {
52-
System.out.print(matrix[i][c] + " ");
56+
result.add(matrix[i][c]);
5357
}
5458
c++;
5559
}
5660

5761
}
58-
62+
return result;
5963
}
6064

61-
public static void main(String[] args) {
62-
int[][] matrix = {
63-
{ 3, 4, 5, 6, 7 },
64-
{ 8, 9, 10, 11, 12 },
65-
{ 14, 15, 16, 17, 18 },
66-
{ 23, 24, 25, 26, 27 },
67-
{ 30, 31, 32, 33, 34 }
68-
};
69-
70-
var printer = new PrintAMatrixInSpiralOrder();
71-
printer.print(matrix, matrix.length, matrix[0].length);
72-
73-
}
7465
}

0 commit comments

Comments
 (0)