题目:
给定一个m x n个元素的矩阵(m行,n列),按螺旋顺序返回矩阵的所有元素。
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
[
[ 1, 2, 3 ],
[ 4, 5, 6 ], Output: [1,2,3,6,9,8,7,4,5]
[ 7, 8, 9 ]
]
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8], Output: [1,2,3,4,8,12,11,10,9,5,6,7]
[9,10,11,12]
]
即,对于矩阵的每一层,从左上角开始,逆时针排列
方法:
类似【剑指offer第二版——面试题29(java)】—— https://blog.csdn.net/qq_22527013/article/details/89641098
从矩阵最外层开始,往里每一层都逆时针遍历,加入到数组中,遍历分为四个部分:
1)在最上,从左往右遍历;2)在最右,从上往下
3)在最下,从右往左;4)最左,从下往上
需要注意边界的是否重复输入或遗漏输入,如下图中四个角的位置,容易出现重复或丢失,需要注意边界
代码:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> re = new LinkedList<Integer>();
if(matrix.length==0 || matrix[0].length==0) {
return re;
}
int i = 0;
int n = (matrix.length>matrix[0].length)?matrix[0].length:matrix.length;
// 按层 由外向内
while(i<n/2+n%2) {
spiral(matrix, i, re);
i++;
}
return re;
}
// 主要功能函数
public void spiral(int[][] matrix, int times,List<Integer> re) {
int m = matrix.length-1;
int n = matrix[0].length-1;
// 本次矩阵边界
int left = times;
int right = n-times;
int up = times;
int down = m-times;
// 如果剩下的是1×1,直接添加
if(left==right && up==down && left==up) {
re.add(matrix[left][up]);
}else {
// 上:从左到右
int loc = left;
while(loc<=right) {
re.add(matrix[up][loc++]);
}
// 右:从上到下
loc = up+1;
while(loc<down) {
re.add(matrix[loc++][right]);
}
// 下:从右到左
loc = right;
while(loc>=left && up<down) {
re.add(matrix[down][loc--]);
}
// 左:从下到上
loc = down-1;
while(loc>up && left<right) {
re.add(matrix[loc--][left]);
}
}
}
}