LeetCode (Spiral Matrix)

xiaoxiao2021-02-28  94

Problem:

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

Solution:

class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ans; if(matrix.empty()) return ans; int m = matrix.size(); int n = matrix[0].size(); if(m == 1) return matrix[0]; for(int i = 0; i < n; i++) ans.push_back(matrix[0][i]); vector<vector<int>> m1; for(int j = n - 1; j >= 0; j--){ vector<int> p; for(int i = 1; i < m; i++) p.push_back(matrix[i][j]); m1.push_back(p); } vector<int> temp = spiralOrder(m1); ans.insert(ans.end(), temp.begin(), temp.end()); return ans; } };

转载请注明原文地址: https://www.6miu.com/read-50566.html

最新回复(0)