10.Spiral Matrix

https://leetcode.com/problems/split-array-largest-sum/

class Solution {
public:
    int d[2][4] = {{1, 0, -1, 0}, {0, 1, 0, -1}};

    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> sol;
        
        int m = matrix.size();
        if (m == 0) {
            return sol;
        }
        int n = matrix[0].size();
        if (n == 0) {
            return sol;
        }
        
        vector<vector<int>> isUsed(m, vector<int>(n, 0));
        
        int x = -1;
        int y = 0;
        int dir = 0;
        int count = m * n;
        
        while (count > 0) {
            int nx = x + d[0][dir];
            int ny = y + d[1][dir];
            
            if (nx < 0 || nx >= n || ny < 0 || ny >= m || isUsed[ny][nx] == 1) {
                dir = (dir + 1) % 4;
                continue;
            }

            count--;
            x = nx;
            y = ny;
            isUsed[y][x] = 1;
            sol.push_back(matrix[y][x]);
        }    
        
        return sol;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,568评论 2 45
  • 今天妈妈开完会回家,检查了我的作业,发现我有3处错误。我改正后妈妈说要跟我聊一聊。妈妈把我叫到身边看着问我,涵涵你...
    荣沛鋡阅读 570评论 1 4
  • 乙型肝炎又称为血清性肝炎、乙型病毒性肝炎(简称乙肝),是由乙型肝炎病(HBV)引起的传染病。其通过血液与体液传播,...
    遇见活在当下的自己阅读 35,431评论 7 0
  • 人生真的有很多种可能性,不知道并不代表不可能,就像每天在我们看不见的地方发生着我们不知道的事情。 ...
    邓秋云阅读 414评论 0 3