My Cpp solution, not very smart


  • 0
    K

    class Solution {
    public:
    // right 0, down 1, left 2, up 3
    void solution(vector<vector<int>>& matrix, int orient, vector<int>& bound, int x, int y, vector<int>& res) {
    if (res.size() >= matrix.size()*matrix[0].size()) {
    return;
    }
    if (orient == 0) {
    if ( y == bound[0]) {
    --bound[0];
    solution(matrix, (orient+1)%4, bound, x+1, y-1, res);
    }
    else {
    res.push_back(matrix[x][y]);
    solution(matrix, orient, bound, x, y+1, res);
    }
    } else if (orient == 1) {
    if (x == bound[1]) {
    --bound[1];
    solution(matrix, (orient+1)%4, bound, x-1, y-1, res);
    }
    else {
    res.push_back(matrix[x][y]);
    solution(matrix, orient, bound, x+1, y, res);
    }
    } else if (orient == 2) {
    if (y == bound[2]) {
    ++bound[2];
    solution(matrix, (orient+1)%4, bound, x-1, y+1, res);
    } else {
    res.push_back(matrix[x][y]);
    solution(matrix, orient, bound, x, y-1, res);
    }
    } else {
    if (x == bound[3]) {
    ++bound[3];
    solution(matrix, (orient+1)%4, bound, x+1, y+1, res);
    } else {
    res.push_back(matrix[x][y]);
    solution(matrix, orient, bound, x-1, y, res);
    }
    }
    }
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> res;
    int m = matrix.size();
    if(m == 0) return res;
    int n = matrix[0].size();

        vector<int> orientBound = {n, m, -1, 0};
        solution(matrix, 0, orientBound, 0, 0, res);
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.