-->

Saturday, February 4, 2017

[LeetCode] 498. Diagonal traverse

https://leetcode.com/contest/leetcode-weekly-contest-18b/problems/diagonal-traverse/

Solution:
This question is pretty straightforward. So it is designed for implementation details, i.e. boundary conditions.

Code:
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty()||matrix.front().empty()) return res;
        int m = matrix.size(), n=matrix.front().size();
        for(int i=0; i<n+m-1; ++i){
            if(!(i%2)){//slop as 1;
                int x = min(i, m-1), y = i-x; //initial position;
                while(x>=0&&y<n) res.push_back(matrix[x--][y++]);
            }
            else{//slop as -1;
                int y = min(i, n-1), x = i-y;//initial position;
                while(x<m&&y>=0) res.push_back(matrix[x++][y--]);
            }
        }
        return res;
    }
};

No comments :

Post a Comment