clueless coding // TODO: be smarter

LeetCode Spiral Matrix: CPP Solution



TL;DR Code Solution


vector<int> spiralOrder(vector<vector<int>>& matrix) {

    vector<int> result;
    if (matrix.size() == 0 || matrix[0].size() == 0) {
        return result;
    }

    int colStart = 0;
    int rowStart = 0;
    int colEnd = (int)matrix[0].size() - 1;
    int rowEnd = (int)matrix.size() - 1;

    while (colStart <= colEnd && rowStart <= rowEnd) {

        for (int i = colStart; i <= colEnd; i++) {
            result.push_back(matrix[rowStart][i]);
        }
        rowStart++;

        for (int i = rowStart; i <= rowEnd; i++) {
            result.push_back(matrix[i][colEnd]);
        }
        colEnd--;

        if (rowStart <= rowEnd) {
            for (int i = colEnd; i >= colStart; i--) {
                result.push_back(matrix[rowEnd][i]);
            }

        }
        rowEnd--;

        if (colStart <= colEnd) {
            for (int i = rowEnd; i >= rowStart; i--) {
                result.push_back(matrix[i][colStart]);
            }
        }
        colStart++;

    }



    return result;

}