Skip to content

Latest commit

 

History

History
55 lines (48 loc) · 1.42 KB

File metadata and controls

55 lines (48 loc) · 1.42 KB

59. Spiral Matrix II

Question:

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Analysis:

维护当前坐标x,y;维护一个dir;每次根据x,y判断dir应该修改成多少;

每次x,y根据dir来增加;dir是direction;发现[0,m]超过边界了,或者填过了,就螺旋形的把

right->down->left->up->right.......

Solution1:C++

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int dir[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        vector<vector<int>> matrix(n, vector<int>(n,0));
        matrix[0][0] = 1;
        int x = 0, y = 0, w = 0, count = 1;
        while (count < n*n){
            count++;
            int i = x + dir[w][0];
            int j = y + dir[w][1];
            if( i < 0 || i >= n || j < 0 || j >= n || matrix[i][j] != 0){
                w = (w + 1) % 4;
            }
            x += dir[w][0];
            y += dir[w][1];
            matrix[x][y] = count;
        }
        for(int i = 0; i <= n-1; i++){
            for(int j = 0; j <= n-1; j++){
                printf("%d",matrix[i][j]);
            }
        }
        return matrix;
    }
};

本题关键:

对于这种画图的题目:统一的方法是设定一个direction,然后用位置更新direction,用direction更新位置,然后像人类一样画图。