Leetcode 54. Spiral Matrix (Medium) (cpp)

来源:互联网 发布:达内和尚观linux哪个好 编辑:程序博客网 时间:2024/06/01 08:53

Leetcode 54. Spiral Matrix (Medium) (cpp)

Tag: Array

Difficulty: Medium


/*54. Spiral Matrix (Medium)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].*/class Solution {public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> res;if (matrix.empty()) {            return res;        }int m = matrix.size() - 1, n = matrix[0].size() - 1, h = 0, l = 0;while (true) {for (int col = l; col <= n; col++) {res.push_back(matrix[h][col]);            }if (++h > m) {                break;            }for (int row = h; row <= m; row++) {res.push_back(matrix[row][n]);            }if (--n < l) {                break;            }for (int col = n; col >= l; col--) {res.push_back(matrix[m][col]);            }if (--m < h) {                break;            }for (int row = m; row >= h; row--) {res.push_back(matrix[row][l]);            }if (++l > n) {                break;            }}return res;}};


0 0