力扣 題目59- 螺旋矩陣 II
阿新 • • 發佈:2022-05-23
題目
題解
在力扣 題目54--螺旋矩陣中我們有了遍歷的方法 那麼我們修改一下然後 遍歷時按照從1開始放入不就可以了
程式碼
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 int side(vector<vector<int>>& result, int up, int down, int left, int right,int add) { 5 if (result.empty() || result[0].empty()) returnView Code{}; 6 for (int i = left; i <= right; i++) { 7 result[up][i]=add; 8 add = add + 1; 9 } 10 if (++up > down) { 11 return 0; 12 } 13 for (int i = up; i <= down; i++) { 14 result[i][right]=add; 15 add = add + 1; 16 } 17 if (--right < left) {18 return 0; 19 } 20 for (int i = right; i >= left; i--) { 21 result[down][i]=add; 22 add = add + 1; 23 } 24 if (--down < up) { 25 return 0; 26 } 27 for (int i = down; i >= up; i--) { 28 result[i][left]=add; 29 add = add + 1; 30 } 31 if (++left > right) { 32 return 0; 33 } 34 side(result, up, down, left, right,add); 35 return 0; 36 } 37 38 class Solution { 39 public: 40 vector<vector<int>> generateMatrix(int n) { 41 vector<vector<int>>result(n, vector<int>(n, 0)); 42 int up = 0, down = n - 1, left = 0, right = n - 1; 43 int add = 1; 44 side(result,up, down, left, right,add); 45 return result; 46 } 47 }; 48 49 int main() { 50 Solution sol; 51 vector<vector<int>> result=sol.generateMatrix(1); 52 for (int i = 0; i < result.size(); i++) { 53 for (int j = 0; j < result[i].size(); j++) { 54 cout << result[i][j] << " "; 55 } 56 cout << endl; 57 } 58 }