Spiral Matrix

原创 2016年08月29日 11:35:19

一、问题描述

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

二、思路

这道题目思路也很简单,由于是m*n个元素,所以只要外层循环中数组中元素小于等于总元素个数即可。内部有四个循环,分别是从左到右、从上到下、从右到左和从下到上,每进行完一个循环都要判断元素书否达到上限m*n,执行完4个循环后需要将i加一。

三、代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> vec;
        if (matrix.empty()) return {};
        int m = matrix.size();
        int n = matrix[0].size();
        int i = 0, sum = m * n,x,y;
        while(vec.size() <= sum){
            x = i;
            for(y = i; y < n -i; ++y)
                vec.push_back(matrix[x][y]);
            if(vec.size() == sum) break;
            
            y = n - i - 1;
            for(x = i + 1; x < m - i; ++x)
                vec.push_back(matrix[x][y]);
            if(vec.size() == sum) break;
            
            x = m - 1 - i;
            for(y = n - 2 - i; y >= i; --y)
                vec.push_back(matrix[x][y]);
            if(vec.size() == sum) break;
            
            y = i;
            for(x = m - 2 - i; x > i;--x)
                vec.push_back(matrix[x][y]);
            if(vec.size() == sum) break;
            
            ++i;
        }
        return vec;
    }
};


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

相关文章推荐

54. Spiral Matrix (有待进一步研究)

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

PAT (Advanced Level) Practise 1105 Spiral Matrix (25)

1105. Spiral Matrix (25) 时间限制 150 ms 内存限制 65536 kB 代码长度限制 16000 B ...

LeetCode-Spiral Matrix

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

[59] Spiral Matrix II

对一个二维数组进行螺旋式填充
  • camlot_
  • camlot_
  • 2015年08月25日 17:38
  • 252

LeetCode054 Spiral Matrix

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

【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: Spiral Matrix 解题报告

转载网址:http://www.tuicool.com/articles/bA3yAf Spiral Matrix Given a matrix of m x n elements (m ...

leetcode--Spiral Matrix II

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

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