给定一个包含 m x n 个要素的矩阵,(m 行, n 列),按照螺旋顺序,返回该矩阵中的所有要素。
样例
给定如下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
应返回 [1,2,3,6,9,8,7,4,5]。
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
思路:使用矩阵的左上角和右下角两对坐标来控制所打印的矩阵。
参考:牛客网左程云老师视频
public class Solution {
/**
* @param matrix a matrix of m x n elements
* @return an integer list
*/
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if(null == matrix || matrix.length == 0 || matrix[0].length == 0) return result;
int li = 0, lj = 0, ri = matrix.length-1, rj = matrix[0].length-1;//分别是左上角和右下角的坐标,控制所打印的环。
while(li <= ri && lj <= rj) {
int i = li, j = lj;
while(j <= rj) {
result.add(matrix[i][j]);
j++;
}
--j;++i;
while(i <= ri) {
result.add(matrix[i][j]);
i++;
}
--i;--j;
while(j > lj && li != ri) {
result.add(matrix[i][j]);
j--;
}
while(i > li && lj != rj) {
result.add(matrix[i][j]);
i--;
}
li++;lj++;ri--;rj--;
}
return result;
}
}