力扣-54.螺旋矩阵
题目链接
54.螺旋矩阵
class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> res = new ArrayList<>();int left = 0;int right = matrix[0].length - 1;int top = 0;int bottom = matrix.length - 1;while (left <= right && top <= bottom) {for (int i = left; i <= right; i++) {res.add(matrix[top][i]);}if (top == bottom) {return res;}top++;for (int i = top; i <= bottom; i++) {res.add(matrix[i][right]);}if (left == right) {return res;}right--;for (int i = right; i >= left; i--) {res.add(matrix[bottom][i]);}bottom--;for (int i = bottom; i >= top; i--) {res.add(matrix[i][left]);}left++;}return res;}
}
小结:这道题的难度在于边界条件,只用一个偏移量会比较复杂,而且在只有一行或者一列的时候容易重复,这里用上下左右四个值来控制偏移量,更加简单清晰。