374. Spiral Matrix

class Solution { public: /** * @param matrix: a matrix of m x n elements * @return: an integer list */ vector<int> spiralOrder(vector<vector<int>> &matrix) { // write your code here vector<int> res; const int m = matrix.size(); if(m == 0){ return res; } const int n = matrix[0].size(); int count = 0; while(count * 2 < n && count * 2 < m){ for(int j = count; j < n - count; j++){ res.push_back(matrix[count][j]); } for(int i = count + 1; i < m - count; i++){ res.push_back(matrix[i][n - 1 - count]); } if(m - 2 * count == 1 || n - 2 * count == 1){ break; } for(int j = n - 2 - count; j >= count; j--){ res.push_back(matrix[m - 1 - count][j]); } for(int i = m - 2 - count; i >= count + 1; i--){ res.push_back(matrix[i][count]); } ++count; } return res; } };

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一