题解 | #牧场边界巡游#

牧场边界巡游

https://www.nowcoder.com/practice/bc7fe78f7bcc49a8bc0afdd7a55ca810

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix int整型vector<vector<>> 
     * @return int整型vector
     */
    vector<int> spiralTravelCounterClockwise(vector<vector<int> >& matrix) {
        // write code here
        int row = matrix.size(), col = matrix[0].size();
        int left = 0, right = col-1, top = 0, bottom = row-1;
        int n = row * col;
        int total = 0;
        vector<int> ans;
        while (total < n) {
            for (int i = top; i <= bottom; i++) {
                ans.push_back(matrix[i][left]);
                total++;
            }
            if (total == n) break;
            left++;
            for (int i = left; i <= right; i++) {
                ans.push_back(matrix[bottom][i]);
                total++;
            }
            bottom--;
            if (total == n) break;
            for (int i = bottom; i >= top; i--) {
                ans.push_back(matrix[i][right]);
                total++;
            }
            right--;
            if (total == n) break;
            for (int i = right; i >= left; i--) {
                ans.push_back(matrix[top][i]);
                total++;
            }
            top++;
        }
        return ans;
    }
};

全部评论

相关推荐

2025-11-17 11:50
已编辑
西南石油大学 数据分析师
菜鸡oider:兄弟,你这个我说实话,我要不是看你上面写的计算机专业,都不知道你要找什么工作
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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