LeetCode 54 - Spiral Matrix

来源:互联网 发布:java图形界面时间控件 编辑:程序博客网 时间:2024/04/30 15:30

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

My Code

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> nums;        int m = matrix.size();        if (m == 0)            return nums;        int n = matrix[0].size();        for (int i = 0; i < (m + 1) / 2; i++)        {            // Up            for (int j = i; j <= n - 1 - i; j++)                nums.push_back(matrix[i][j]);            // Right            if (n - 1 - i >= 0 && n - 1 - i >= i)                for (int j = i + 1; j <= m - 2 - i; j++)                    nums.push_back(matrix[j][n-1-i]);            // Below            if (m - 1 - i > i)                for (int j = n - 1 - i; j >= i; j--)                    nums.push_back(matrix[m-1-i][j]);            // Left            if (n - 1 - i > i)                for (int j = m - 2 - i; j >= i + 1 ; j--)                    nums.push_back(matrix[j][i]);        }        return nums;    }};
Runtime: 0 ms

0 0