最直观的思路,想象自己站在棋盘上来螺旋前进,碰壁后回退一步并旋转方向

螺旋矩阵

http://www.nowcoder.com/questionTerminal/7edf70f2d29c4b599693dc3aaeea1d31

时间复杂度O(N), 空间复杂度O(N)
需要记录每个数据是否被访问,记录已经访问的数据个数
想象自己站在棋盘上来螺旋前进,每次碰壁后回退一步并调整方向即向右旋转90°,直到所有数据访问完毕

class Solution {
    vector<vector<int>> dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        int m = matrix.size();
        if(m == 0) return {};
        int n = matrix[0].size();
        if(n == 0) return {};
        vector<vector<int>> visited(m, vector<int>(n));
        int cnt = m * n;
        vector<int> ret;
        int x = 0, y = -1, i = 0;
        while(cnt) {
            x += dir[i][0];
            y += dir[i][1];
            if(x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) {
                x -= dir[i][0];
                y -= dir[i][1];
                i = ++i % 4;
            }
            else {
                --cnt;
                ret.push_back(matrix[x][y]);
                visited[x][y] = 1;
            }
        }
        return ret;
    }
};
全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务