leetcode_c++:Spiral Matrix(054)

原创 2016年05月31日 00:15:37

题目

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


算法

复杂度:O(nm)


class Solution{
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix){
        vector<int> result;
        if(matrix.empty()) 
            return result;
        int beginX=0,endX=matrix[0].size()-1;
        int beginY=0,endY=matrix.size()-1;

        while(true){
            //from left to right
            for(int i=beginX;i<=endX;++i)
                result.push_back(matrix[beginY][i]);
            if(++beginY>endY)  break;

            //from top to down
            for(int i=beginY;i<=endY;++i)
                result.push_back(matrix[i][endX]);
            if(beginX>--endX)  break;

            //form right to left
            for(int i=endX;i>=beginX;--i)
                result.push_back(matrix[endY][i]);
            if(beginY>--endY)  break;

            //form bottom to up
            for(int i=endY;i>=beginY;--i)
                result.push_back(matrix[i][beginX]);
            if(++beginX>endX) break;

        }

        return result;

    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode054 Spiral Matrix

详细见:leetcode.com/problems/spiral-matrix Java Solution: github package leetcode; import java...
  • zxwtry
  • zxwtry
  • 2017年04月10日 22:10
  • 85

【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix(螺旋矩阵)】

【054-Spiral Matrix(螺旋矩阵)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a matrix of m x n elements (m r...

[C++]LeetCode: 110 Spiral Matrix (螺旋输出矩阵元素)

题目: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in sp...

[C++]LeetCode: 111 Spiral Matrix II (螺旋写入矩阵)

题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order....

牛客:剑指offer:顺时针打印矩阵 (Java)(同leetcode的spiral matrix i 和ii)

题目描述: 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1 2 3 45 6 7 89 10 11 1213 14 15 16则依次打印出数字1,2,3,4,...

leetcode-54 Spiral Matrix 顺时针打印矩阵(《剑指offer》面试题20)

问题描述: Given a matrixof m x n elements (m rows, n columns),return all elements of the matrix in spira...

LeetCode-Spiral Matrix

题目链接:https://oj.leetcode.com/problems/spiral-matrix/ 题目内容: Given a matrix of m x n elements (m rows...

【leetcode】【54】Spiral Matrix

一、问题描述 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix ...

leetcode-java-54. Spiral Matrix

/* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral...

[LeetCode]--59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For e...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode_c++:Spiral Matrix(054)
举报原因:
原因补充:

(最多只允许输入30个字)