54. Spiral Matrix
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int top = 0;
int bottom = matrix.length-1;
int left = 0;
int right= matrix[0].length-1;
List<Integer> res = new LinkedList<Integer>();
while(true){
for (int j = left; j<=right; j++){
res.add(matrix[top][j]);
}
top++;
if (top>bottom) break;
for(int i = top; i<=bottom; i++){
res.add(matrix[i][right]);
}
right--;
if(left>right) break;
for(int j = right; j>=left; j--){
res.add(matrix[bottom][j]);
}
bottom--;
if (top>bottom) break;
for(int i=bottom; i>=top; i--){
res.add(matrix[i][left]);
}
left++;
if(left>right) break;
}
return res;
}
}
Last updated
Was this helpful?