原题:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For 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].
即将给定的矩阵按顺时针顺序将元素输出。
思考过程:一开始想到每一环都限制住四个顶点进行遍历,然后递归遍历里面的子矩阵。后来想到不用那么复杂,先一环环遍历矩阵,每次遍历都一次遍历它的最上边、最右边、最下边、最左边,而且一定要注意重复问题。
AC代码:
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ret = new ArrayList<>();
int lenOfColumn = matrix.length;
if (lenOfColumn == 0) return ret;
int lenOfRow = matrix[0].length;
for (int i = 0;i < (Math.min(lenOfColumn,lenOfRow) + 1) / 2;i++) {//一圈圈循环矩阵
int right = lenOfRow - i - 1;//此次遍历的矩阵的最右边,最左边和最上边都由i控制
int bottom = lenOfColumn - i - 1;//此次遍历的矩阵的最下边
for (int j = i;j <= right;j++)//先遍历最上面的一行
ret.add(matrix[i][j]);
for (int j = i + 1;j <= bottom;j++)//遍历最右面一行,注意重复
ret.add(matrix[j][right]);
if (i != bottom)//如果只剩一行,容易出现重复,下同
for (int j = right - 1;j >= i;j--)//遍历最下面一行,注意重复
ret.add(matrix[bottom][j]);
if (i != right)
for (int j = bottom - 1;j > i;j--)//遍历最左面一行,注意重复
ret.add(matrix[j][i]);
}
return ret;
}
本文介绍了一种算法,用于按顺时针螺旋顺序遍历给定的二维矩阵,并提供了详细的实现思路及AC代码。
374

被折叠的 条评论
为什么被折叠?



