[leetcode_59] Spiral Matrix II

输出螺旋增长的矩阵,两次 AC 注意 n=0 的情况

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<vector<int>> ans(n);
        if(n == 0)
        {
            ans.clear();
            return ans;
        }
        int **map = new int*[n];
        for(int i = 0; i < n; i++)
        {
            map[i] = new int[n];
        }
        int val = 1;
        int x = 0;
        int y = 0;
        int dir = 1; // 1 右 2 下 3 左 4 上
        int r1 = -1;
        int r2 = n;
        int l1 = -1;
        int l2 = n;
        while(true)
        {
            map[x][y] = val;
            switch(dir)
            {
                case 1:
                    y++;
                    if(y == l2)
                    {
                        dir = 2;
                        y--;
                        x++;
                        r1++;
                    }
                    break;
                case 2:
                    x++;
                    if(x == r2)
                    {
                        dir = 3;
                        x--;
                        y--;
                        l2--;
                    }
                    break;
                case 3:
                    y--;
                    if(y == l1)
                    {
                        dir = 4;
                        y++;
                        x--;
                        r2--;
                    }
                    break;
                case 4:
                    x--;
                    if(x == r1)
                    {
                        dir = 1;
                        x++;
                        y++;
                        l1++;
                    }
                    break;
            }
            if(val == n*n)
                break;
            val++;
        }
        for(int i = 0; i < n; i++)
        {
            vector<int> tmp(n);
            for(int j = 0; j < n; j++)
            {
                tmp[j] = map[i][j];
            }
            ans[i] = tmp;
        }
        return ans;
    }
};
Licensed under CC BY-NC-SA 4.0