给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
这种题型应该需要注意一下几个点
- 起始位置
- 运动方向
- 结束标志
- 边界
开始分析:
- 起始位置
很明显其实位置是[0,0] - 运动方向
右→下→左→上 循环 - 结束标志
输出list的长度等于需要输出元素的数量 - 边界
到最右边时 top++
到最下边时 right–
到最左边时 bottom–
到最上边时 left++
下附java运行代码
package isLeetcode;
import java.util.ArrayList;
import java.util.List;
public class Solution315 {
public static List<Integer> spiralOrder(int[][] matrix) {
int m=matrix.length; //纵向长度
int n=matrix[0].length;//横向长度
List<Integer> order = new ArrayList<Integer>();
//边界
int left =0;
int right=n-1;
int top=0;
int bottom=m-1;
//方向
int cur_d=0; //0右 1下 2左 3上
int [][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; //移动方向对应的数据加减
//目前位置下标
int x=0,y=0; //x为纵 y为横
//arr数组存放标记
int i=0;
while(order.size()!=m*n){
order.add(matrix[x][y]);
i++;
if(cur_d==0 && y==right){ //到达右边界
cur_d++;
top++;
}else if(cur_d==1 && x==bottom){ //到达下边界
cur_d++;
right--;
}else if(cur_d==2 && y==left){ //到达左边界
cur_d++;
bottom--;
}else if(cur_d==3 && x==top){ //到达上边界
cur_d++;
left++;
}
cur_d %=4;
x+=dirs[cur_d][0];
y+=dirs[cur_d][1];
}
return order;
}
public static void main(String[] args) {
int [][]arr={{1,2,3},{4,5,6},{7,8,9}};
System.out.println(spiralOrder(arr));
}
}
此文章创于本人学习时的记录,如有错误或更优解还请指出。