题解 | #螺旋矩阵#

螺旋矩阵

http://www.nowcoder.com/questionTerminal/ac5544ee0d7247a4ba75e00793c71907

public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 
     * @param matrix int整型vector<vector<>> 
     * @return int整型vector
     */
    vector<int> SpiralMatrix(vector<vector<int> >& matrix) {
        vector<int> res;
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return res;
        }

        int row = matrix.size(), col = matrix[0].size();
        int left = 0, right = col - 1, top = 0, bottom = row - 1;
        while (left <= right && top <= bottom) {
            for (int j = left; j <= right; j++)   res.push_back(matrix[top][j]);
            for (int i = top + 1; i <= bottom; i++)   res.push_back(matrix[i][right]);
            if (left < right && top < bottom) {
                for (int j = right - 1; j > left; j--)   res.push_back(matrix[bottom][j]);
                for (int i = bottom; i > top; i--)   res.push_back(matrix[i][left]);
            }
            ++left;
            --right;
            ++top;
            --bottom;
        }
        return res;
    }
};
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务