力扣 題目54--螺旋矩陣
阿新 • • 發佈:2022-05-17
題目
題解
找四個邊的範圍然後根據規律放入即可
程式碼
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 int side(vector<vector<int>>& matrix, vector<int>& result, int m, int n, int up, int down, int left, int right) { 5 if (matrix.empty() || matrix[0].empty()) returnView Code{}; 6 for (int i = left; i <= right; i++) { 7 result.push_back(matrix[up][i]); 8 } 9 if (++up > down) { 10 return 0; 11 } 12 for (int i = up; i <= down; i++) { 13 result.push_back(matrix[i][right]); 14 } 15 if (--right < left) { 16 return0; 17 } 18 for (int i = right; i >= left; i--) { 19 result.push_back(matrix[down][i]); 20 } 21 if (--down < up) { 22 return 0; 23 } 24 for (int i = down; i >= up; i--) { 25 result.push_back(matrix[i][left]); 26 } 27 if (++left > right) {28 return 0; 29 } 30 side(matrix, result, m, n, up, down, left, right); 31 return 0; 32 } 33 class Solution { 34 public: 35 vector<int> spiralOrder(vector<vector<int>>& matrix) { 36 vector<int> result; 37 int m = matrix.size(), n = matrix[0].size(); 38 int up = 0, down = m - 1, left = 0, right = n - 1; 39 side(matrix, result, m, n, up, down, left, right); 40 return result; 41 } 42 }; 43 int main() { 44 vector<vector<int>> matrix = { {1, 2, 3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16} }; 45 Solution sol; 46 vector<int> result=sol.spiralOrder(matrix); 47 for (int i = 0; i < result.size(); i++) { 48 cout << result[i]<<endl; 49 } 50 51 }