矩阵的螺旋遍历

矩阵的螺旋遍历

问题

这个题目说的是,给你一个 m x n 的矩阵,你要对它进行螺旋遍历,然后返回遍历结果。

比如说给你的矩阵 a 是:

1, 2, 3
4, 5, 6
7, 8, 9

螺旋遍历它得到:

1, 2, 3, 6, 9, 8, 7, 4, 5

因此你要返回以上序列。

代码

public class AlgoCasts {

  // Time: O(m*n), Space: O(1)
  public List<Integer> spiralOrder(int[][] matrix) {
    if (matrix == null || matrix.length == 0 ||
      matrix[0] == null || matrix[0].length == 0)
      return new ArrayList<>();

    List<Integer> result = new ArrayList<>();
    int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
    while (true) {
      for (int i = left; i <= right; ++i) result.add(matrix[top][i]);
      if (++top > bottom) break;

      for (int i = top; i <= bottom; ++i) result.add(matrix[i][right]);
      if (--right < left) break;

      for (int i = right; i >= left; --i) result.add(matrix[bottom][i]);
      if (--bottom < top) break;

      for (int i = bottom; i >= top; --i) result.add(matrix[i][left]);
      if (++left > right) break;
    }
    return result;
  }

}

  转载请注明: ForwardXu 矩阵的螺旋遍历

 上一篇
树 t 是否等于树 s 的子树 树 t 是否等于树 s 的子树
树 t 是否等于树 s 的子树问题 这个题目说的是,给你两棵二叉树 s 和 t,你要判断 t 是否与 s 的某一棵子树结构相同,并且节点上的值也相等。 比如说,给你的第一棵树 s 是: 1 / \ 2 4
2019-02-26
下一篇 
有序链表转换二叉搜索树 有序链表转换二叉搜索树
有序链表转换二叉搜索树问题 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 给定的有序链表: [-10, -3, 0, 5
2019-02-21
  目录