本文共 1929 字,大约阅读时间需要 6 分钟。
二维数组的顺时针螺旋遍历是一种常见的算法问题,主要用于遍历矩阵中的元素按照特定顺序排列。以下是优化后的详细解释和解决方案:
顺时针螺旋遍历的核心思想是逐层从矩阵的外向内遍历,每一层都按顺时针方向收缩矩阵范围。具体来说,每一层包括四个步骤:
通过逐步收缩矩阵范围(即调整top、bottom、left、right指针),可以层层递进地遍历整个矩阵。
import java.util.ArrayList;import java.util.List;public class Solution { public List spiralOrder(int[][] matrix) { List res = new ArrayList<>(); if (matrix.length == 0) { return res; } int top = 0; int bottom = matrix.length - 1; int left = 0; int right = matrix[0].length - 1; while (top <= bottom && left <= right) { // 左到右遍历顶行 for (int i = left; i <= right; i++) { res.add(matrix[top][i]); } top++; // 上到下遍历右列 for (int i = top; i <= bottom; i++) { res.add(matrix[i][right]); } right--; // 右到左遍历底行 if (top <= bottom) { // 确保还有行存在 for (int i = right; i >= left; i--) { res.add(matrix[bottom][i]); } bottom--; } // 下到上遍历左列 if (left <= right) { // 确保还有列存在 for (int i = bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; } } return res; }} top、bottom、left、right指针分别初始化为矩阵的顶行、底行、左列和右列。top未超过bottom且left未超过right,继续循环处理每一层。top指针向下移动。right指针向左移动。bottom指针向上移动。left指针向右移动。假设输入矩阵为:
1 2 34 5 67 8 9
按照上述算法,输出顺序应该是:1, 2, 3, 6, 9, 8, 7, 4, 5。
通过以上方法,可以高效地实现二维数组的顺时针螺旋遍历,适用于处理类似的问题。
转载地址:http://nsog.baihongyu.com/