思路:
先规定好四个角的位置,再按照题目的顺序遍历添加元素,每遍历完一圈,四个角也同时做相应的操作实现缩小一圈,在四个角上下左右都到一个点时遍历完毕。
实现:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
ArrayList<Integer> list = new ArrayList<Integer>();
if(row==0||col==0)return list;
int left = 0;//左1
int top = 0;//上1
int right = col-1;//右1
int bottom = row-1;//下1
while(left<=right && top<=bottom){
for(int i=left;i<=right;i++)list.add(matrix[top][i]);//遍历添加top行的元素
for(int i=top+1;i<=bottom;i++)list.add(matrix[i][right]);//遍历添加right列的元素
if(top!=bottom)//判断还有没有上下行
for(int i=right-1;i>=left && top<bottom;i--)list.add(matrix[bottom][i]);//倒序遍历添加bottom行元素,加判断top<bottom是为了防止只有一行数据的情况
if(left!=right)//判断每行还有没有元素
for(int i=bottom-1;i>top && right>left;i--)list.add(matrix[i][left]);//倒序遍历添加left列元素,加判断top<bottom是为了防止只有一行数据的情况
left++;
top++;
right--;
bottom--;
//范围缩小一圈,继续遍历
}
return list;
}
}
// 0 1 2 3
//0 1 2 3 4
//1 5 6 7 8
//2 9 10 11 12
//3 13 14 15 16