LeetCode之54. Spiral Matrix

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].

题目大意

给一个矩阵,按照螺旋顺序返回矩阵的所有元素。

算法分析

按照从→ ↓ ←↑循环遍历整个矩阵。

代码如下
  • Java
public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resultList = new ArrayList<>();
        if (matrix.length == 0)
            return resultList;
        int left = 0;
        int right = matrix[0].length-1;
        int up = 0;
        int down = matrix.length-1;
        while (left<=right && up<=down) {
            for (int j=left; j<=right; j++) {
                resultList.add(matrix[up][j]);
            }
            up++;

            for (int j=up; j<=down; j++) {
                resultList.add(matrix[j][right]);
            }
            right--;

            if (up<=down) {
                for (int j=right;j>=left;j--) {
                    resultList.add(matrix[down][j]);
                }
            }
            down--;

            if (left<=right) {
                for (int j=down;j>=up;j--) {
                    resultList.add(matrix[j][left]);
                }
            }
            left++;
        }
        return resultList;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 文/我的日子写成诗 曾经,她也是被捧在手心里的宝贝 后来,有了我们阿,她又成了英勇的战士 其实,她也是爱美想撒娇偶...
    我的日子写成诗阅读 438评论 0 4
  • 阿弥陀佛!诸位善知识今天我们继续共同学习受持《般若波罗蜜多心经》!感恩法缘殊胜!感恩法缘大慈!感恩因缘和合 !感恩...
    了悟菩提阅读 712评论 0 0
  • 找比喻 1.她穿着乳白冰纹绉的单袍子,粘在身上,像牛奶的薄膜,肩上也染了一点胭脂晕。 2.霜浓月薄的银蓝的夜里,惟...
    云文_3866阅读 162评论 1 1
  • 对于所追求的理想需带有清心寡欲之态。 ——因为只有纯粹,才可能隽永。 摘自《美好永远得...
    游女Lynsey阅读 246评论 0 0