We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2b41cf2 commit 22ca144Copy full SHA for 22ca144
printElementsInSpiralOrder
@@ -0,0 +1,28 @@
1
+static String printElementsInSpiralOrder(int[][] matrix) { //time complexity: O(n)
2
+ String result = null;
3
+ List ans = new ArrayList<>();
4
+ if(matrix.length != 0){
5
+ int r1 = 0, r2 = matrix.length-1;
6
+ int c1 = 0, c2 = matrix[0].length-1;
7
+ while(r1<=r2 && c1<=c2){
8
+ for(int c=c1;c<=c2;c++)
9
+ ans.add(matrix[r1][c]);
10
+ for(int r = r1+1;r<=r2;r++)
11
+ ans.add(matrix[r][c2]);
12
+
13
+ if(r1<r2 && c1<c2){
14
+ for(int c = c2-1;c> c1;c--)
15
+ ans.add(matrix[r2][c]);
16
+ for(int r=r2;r> r1;r--)
17
+ ans.add(matrix[r][c1]);
18
+ }
19
+ r1++;
20
+ r2--;
21
+ c1++;
22
+ c2--;
23
24
25
26
+ result = ans.toString().replace(",", "");
27
+ return result;
28
0 commit comments