前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 54 Spiral Matrix

Leetcode 54 Spiral Matrix

作者头像
triplebee
发布2018-01-12 15:03:34
4820
发布2018-01-12 15:03:34
举报

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:

代码语言:javascript
复制
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Subscribe to see which companies asked this question

旋转取数,模拟,注意边界情况

代码语言:javascript
复制
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        int m=matrix.size();
        if(m==0) return result;
        int n=matrix[0].size(),x=0,y=0;
        for(;x<m && y<n;x++,y++,m--,n--)
        {
            for(int i=y;i<n;i++) result.push_back(matrix[x][i]);
            for(int i=x+1;i<m;i++) result.push_back(matrix[i][n-1]);
            for(int i=n-2;i>=y && x!=m-1;i--) result.push_back(matrix[m-1][i]);//x==m-1时此行已填
            for(int i=m-2;i>x && y!=n-1;i--) result.push_back(matrix[i][y]);//i>x,因为首行第一个元素开始已填
        }
        return result;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档