DAY 4
0
AI & Data

## 找LeetCode上簡單的題目來撐過30天啦(DAY4)

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:
• m == matrix.length
• n == matrix[i].length
• 1 <= m, n <= 10
• -100 <= matrix[i][j] <= 100

``````class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int  i,j,x,y,count=0;
List<Integer>  result = new ArrayList<>();
y = matrix.length;
x = matrix[0].length;
//System.out.println(x);
//System.out.println(y);
//System.out.println("1" + matrix[i][j]);
int ax=0,ay=0,bx=x-1,by=1,cx=x-2,cy=y-1,dx=0,dy=y-2;

while(count != (x*y)){
for(i=ax,j=ax;j<=bx;j++){
count++;
}
if(count == (x*y)){
break;
}
j=bx;
ay++;
ax++;

for(i=by;i<=cy;i++){
count++;
}
if(count == (x*y)){
break;
}
i=cy;
bx--;
by++;

for(j=cx;j>=dx;j--){
count++;
}
if(count == (x*y)){
break;
}
j=dx;
cy--;
cx--;

for(i=dy;i>=ax;i--){
count++;
}
if(count == (x*y)){
break;
}
dx++;
dy--;
}
return result;
}
}
``````

DAY4心得