题目:力扣https://leetcode-cn.com/problems/spiral-matrix/
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
int top = 0;
int bottom = matrix.length-1;
int left = 0;
int right = matrix[0].length-1;
int count = matrix.length*matrix[0].length;
while(count>0){
//右
for(int i=left ; i<=right&&count>0 ; i++){
ans.add(matrix[top][i]);
count--;
}
top++;
//下
for(int j=top ; j<=bottom&&count>0 ; j++){
ans.add(matrix[j][right]);
count--;
}
right--;
//左
for(int k=right ; k>=left&&count>0 ; k--){
ans.add(matrix[bottom][k]);
count--;
}
bottom--;
//上
for(int l=bottom ; l>=top&&count>0 ; l--){
ans.add(matrix[l][left]);
count--;
}
left++;
}
return ans;
}
}
思路:这道题理解题目不难,但是真要实现出来还是有些困难。解题思路是,一层一层的抽丝剥茧般的读取数据。用top、bottom、left、right四个变量控制边界,按照往右->往下->往左->往上的顺序顺时针走,并用count记录未读取的个数。每一次读取完一层,则修改控制对应边界的变量,直至读完所有数据。
1.声明变量。ans用于存储答案;top为上边界;bottom为下边界;left为左边界;right为右边界;count为未读数据的数量。
List<Integer> ans = new ArrayList<Integer>();
int top = 0;
int bottom = matrix.length-1;
int left = 0;
int right = matrix[0].length-1;
int count = matrix.length*matrix[0].length;
2.按一定的规则(省略号省略的部分则是“一定的规则”)遍历所有元素。
while(count>0){
//......
}
3.按顺时针(右-下-左-上)的方向逐一读取数据,每读完一个数据则更新count的值,每读完一条边则更新对应的变量(top/bottom/left/right)。读到数据时,将其填入ans列表中去。
//右
for(int i=left ; i<=right&&count>0 ; i++){
ans.add(matrix[top][i]);
count--;
}
top++;
//下
for(int j=top ; j<=bottom&&count>0 ; j++){
ans.add(matrix[j][right]);
count--;
}
right--;
//左
for(int k=right ; k>=left&&count>0 ; k--){
ans.add(matrix[bottom][k]);
count--;
}
bottom--;
//上
for(int l=bottom ; l>=top&&count>0 ; l--){
ans.add(matrix[l][left]);
count--;
}
left++;
4.完成上述操作,最后将该列表返回即可。
return ans;