Skip to content

Commit

Permalink
Time: 0 ms (100%), Space: 41.6 MB (28.63%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Amit-S-Sahu committed Oct 22, 2024
1 parent 41cb624 commit 65db079
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions 0054-spiral-matrix/0054-spiral-matrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int top = 0;
int right = matrix[0].length - 1;
int bottom = matrix.length - 1;
int left = 0;

List<Integer> ans = new ArrayList<>();

while (top <= bottom && left <= right) {
// L -> R
for (int i = left; i <= right; i++) {
ans.add(matrix[top][i]);
}
top++;

// U -> D
for (int i = top; i <= bottom; i++) {
ans.add(matrix[i][right]);
}
right--;

if (top <= bottom) {
// R -> L
for (int i = right; i >= left; i--) {
ans.add(matrix[bottom][i]);
}
bottom--;
}

if (left <= right) {
// D -> U
for (int i = bottom; i >= top; i--) {
ans.add(matrix[i][left]);
}
left++;
}
}
return ans;
}
}

0 comments on commit 65db079

Please sign in to comment.