Leetcode54. Spiral Matrix
题目描述
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
思路
有四个方向right, left, top, bottom.
- direction=“right”, 当到达最右边界时,代表本行输出结束,top++,
- direction=“bottom”,当到达最下边界时, right–,
- direction = “left”,当到达最左边界是 bottom–,
- direction=“top”,当到达top时候,left++,direction=“right”.
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//result
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) return result;
//获取行数---Y行
int lenY =matrix.length;
//获取列数---X列
int lenX = matrix[0].length;
String direction = "right";
int left=0;
int right = lenX-1;
int down =0;
int up = lenY-1;
while(left<=right && down<=up){
if(direction == "right"){
for(int i=left;i<=right;i++){
result.add(matrix[down][i]);
}
down++;
direction = "down";
}else if(direction=="down"){
for(int i=down;i<=up;i++){
result.add(matrix[i][right]);
}
right--;
direction = "left";
}else if(direction=="left"){
for(int i=right;i>=left;i--){
result.add(matrix[up][i]);
}
up--;
direction ="up";
}else if(direction=="up"){
for(int i=up;i>=down;i--){
result.add(matrix[i][left]);
}
left++;
direction = "right";
}
}
return result;
}
}