Skip to main content

Leetcode 54

· 2 min read
Junhe Chen

Working with matrix can be challenging, in this question, the main thing is attention to detail, making sure adding no duplicate items and shrink the boundry.

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
int up = 0;
int down = m - 1;
int left = 0;
int right = n - 1;

while(res.size() < m * n){
// there is more item to traverse
// first we add everthing from left to right
for(int i = left; i <= right; i ++){
res.add(matrix[up][i]);
}
// now we add from up to down
for(int j = up + 1; j <= down; j ++){
res.add(matrix[j][right]);
}
// going from right to left but we got to make sure up != down that way we not adding duplicate row
if(up != down){
for(int i = right - 1; i >= left; i --){
res.add(matrix[down][i]);
}
}
// from bot to top
if(left != right){
// note we dont want to add matrix[up][left] it is added from the left to right traversal!
for(int j = down - 1; j > up; j --){
res.add(matrix[j][left]);
}
}

// now we just have to shrink the boundry
left ++;
right --;
up ++;
down --;
}
return res;
}
}