设定上下左右四条边界,分成四种路径:
1、向右移动,直到左边界,遍历上边界,上边界+1
2、向下移动,直到下边界,遍历右边界,右边界-1
3、向左移动,直到左边界,遍历下边界,下边界-1
4、向上移动,直到上边界,遍历左边界,左边界+1
由于长宽不一定相等,所以左右移动时也需要保证上边界小于等于下边界,同样上下移动时,也要保证左边界小于等于右边界。
List<Integer>list = new ArrayList<Integer>();
int m = matrix.length;
int n = matrix[0].length;
int up = 0;
int down = m-1;
int right = n-1;
int left = 0;
while(up<=down&&left<=right){
for(int i=left;i<=right&&up<=down;i++){
list.add(matrix[up][i]);
}
up++;
for(int i=up;i<=down&&left<=right;i++){
list.add(matrix[i][right]);
}
right--;
for(int i=right;i>=left&&up<=down;i--){
list.add(matrix[down][i]);
}
down--;
for(int i=down;i>=up&&left<=right;i--){
list.add(matrix[i][left]);
}
left++;
}
return list;