leetcode || Spiral Matrix

problem:

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].

Hide Tags
  Array
题意:顺时针螺旋输出矩阵

thinking: 

(1)首先想到方法是DFS,把外圈的数字输出之后,矩阵的行和列都缩减了2。递归调用。思路简单。

实现类似于:http://blog.csdn.net/hustyangju/article/details/44812157

(2)全局搜索,考虑用DFS。

与方法一类似,仅仅是DFS思路略有不同,这里參考:http://www.cnblogs.com/remlostime/archive/2012/11/18/2775708.html

一直关注他的实现。简洁高效,膜拜中

开一个数组用来保存。之前这个单元是否被使用过,并配合边界推断,DFS,最后得出结果。

空间复杂度O(n*m),时间O(n*m)

code:

class Solution {
private:
    int step[4][2];
    vector<int> ret;
    bool canUse[100][100];
public:
    void dfs(vector<vector<int> > &matrix, int direct, int x, int y)
    {
        for(int i = 0; i < 4; i++)
        {
            int j = (direct + i) % 4;
            int tx = x + step[j][0];
            int ty = y + step[j][1];
            if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty])
            {
                canUse[tx][ty] = false;
                ret.push_back(matrix[tx][ty]);                
                dfs(matrix, j, tx, ty);               
            }            
        }
    }
    
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        step[0][0] = 0;
        step[0][1] = 1;
        step[1][0] = 1;
        step[1][1] = 0;
        step[2][0] = 0;
        step[2][1] = -1;
        step[3][0] = -1;
        step[3][1] = 0;
        ret.clear();
        memset(canUse, true, sizeof(canUse));
        dfs(matrix, 0, 0, -1);
        
        return ret;
    }
};


转载于:https://www.cnblogs.com/lcchuguo/p/5061000.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值