其他分享
首页 > 其他分享> > 力扣 题目59- 螺旋矩阵 II

力扣 题目59- 螺旋矩阵 II

作者:互联网

题目

题解

力扣 题目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()) return {};
 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 }
View Code

 

 

标签:力扣,59,int,up,II,add,result,down,left
来源: https://www.cnblogs.com/zx469321142/p/16300014.html