本文共 2444 字,大约阅读时间需要 8 分钟。
为了给定矩阵按顺时针螺旋顺序遍历所有元素,可以使用边界变量控制逐层处理四个方向的移动。具体步骤如下:
以下是实现:
class Solution { public ListspiralOrder(int[][] matrix) { List result = new ArrayList<>(); int m = matrix.length; if (m == 0) return result; int n = matrix[0].length; int[] visited = new int[m][n]; int left = 0, right = n - 1, top = 0, bottom = m - 1; int count = 0; while (left <= right && top <= bottom) { // Right pass for (int j = left; j <= right; j++) { if (count >= m * n) break; if (visited[top][j] == 0) { result.add(matrix[top][j]); visited[top][j] = 1; count++; } } top++; // Bottom pass for (int i = top; i <= bottom; i++) { if (count >= m * n) break; if (visited[i][right] == 0) { result.add(matrix[i][right]); visited[i][right] = 1; count++; } } right--; // Left pass if (top <= bottom) { for (int j = right; j >= left; j--) { if (count >= m * n) break; if (visited[bottom][j] == 0) { result.add(matrix[bottom][j]); visited[bottom][j] = 1; count++; } } bottom--; } // Up pass if (left <= right) { for (int i = bottom; i >= top; i--) { if (count >= m * n) break; if (visited[i][left] == 0) { result.add(matrix[i][left]); visited[i][left] = 1; count++; } } } } return result; }}
left
, right
, top
, bottom
变量来控制当前的遍历范围。left
到right
处理每一行的元素,沿着右方向移动。对每个未访问的元素进行标记并加入结果。top
到bottom
行的右边缘(right
),对每个未访问的元素标记并加入结果。right
到left
,处理下一行(bottom
)。bottom
到top
,处理左边缘(left
)。这种方法确保每一层被正确处理,并逐步收缩到矩阵的核心,避免重复访问任何元素,确保按照顺时针螺旋顺序遍历整个矩阵。
转载地址:http://xegyk.baihongyu.com/