leetcode 885. Spiral Matrix III

题目链接

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

题解:

Medium的题无需多言,直接上代码:

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        int drc[4][2] = {{0,1},{1,0},{0,-1},{-1,0}},dn = 0, dp[2] = {1,1}, end = rows*cols, ln=0;
        vector<vector<int>> rst(end, {0,0});
        rst[ln][0] = rStart;
        rst[ln++][1] = cStart;
        while(ln < end) {
            for(int i = 0; i< dp[dn&1]; i++) {
                rStart += drc[dn][0];
                cStart += drc[dn][1];
                if (isInMatrix(rStart, rows) && isInMatrix(cStart, cols)) {
                    rst[ln][0] = rStart;
                    rst[ln++][1] = cStart;
                }
            }
            ++dp[dn&1];
            (++dn) %= 4;
        }
        return rst;
    }
    inline bool isInMatrix(int x, int ln) {
        return x>= 0 && x <ln;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值