LeetCode: Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

我的想法是模拟,就像机器人走路一样,遇到障碍就右转。但是右转的代码有点儿不太直观。

另一种方法我觉得比较好,是就像rotate 90°那样一圈一圈来,从外到里,不需要额外的空间。


class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> res;
        int rows = matrix.size();
        if(rows ==0) return res;
        int cols = matrix[0].size();
        vector<vector<bool> > visit(rows + 2, vector<bool>(cols + 2,false));
        for(int i = 0; i< rows +2; ++i){
            visit[i][0] = true;
            visit[i][cols + 1] = true;
        }
        for(int i = 0; i< cols +2; ++i){
            visit[0][i] = true;
            visit[rows + 1][i] = true;
        }
        int count = rows * cols;
        int pos_x = 0;
        int pos_y = 0;
        int step_x = 0;
        int step_y = 1;
        while(count){
            res.push_back(matrix[pos_x][pos_y]);
            visit[pos_x+1][pos_y+1] = true;
            int next_x = pos_x + step_x;
            int next_y = pos_y + step_y;
            if(visit[next_x + 1][next_y + 1] == true){
                if(step_x){
                    step_y = step_y - step_x;
                    step_x = 0;
                }
                else{
                    step_x = step_y - step_x;
                    step_y =0;
                }
                next_x = pos_x + step_x;
                next_y = pos_y + step_y;
            }
            pos_x = next_x;
            pos_y = next_y;
            count--;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值