您的位置:首页 > 编程语言 > Go语言

Leetcode 498. Diagonal Traverse

2017-11-19 15:18 218 查看
// Problem Reference: https://leetcode.com/problems/diagonal-traverse
/*

My sulotion:
Sets up x-y coordinates with the matrix.
So, it only needs to find the start point & end point with their xy coordinate.
Then, it is clear that the answer is moving orderly from start to end on diagonal.
*/

class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
// Store answer.
vector<int> ans;

// Get bundary value.
int ymax=matrix.size();
if (ymax == 0) {
return ans;
}
int xmax=matrix[0].size();

// Define method moving from start to the end.
// And distinction between odd and even diagonal is made.
int xf[2] = {1, -1};
int yf[2] = {-1, 1};

// Represent the start or end points.
int xn[2],yn[2];

// Go through all diagonals.
for (int i=0; i<xmax+ymax-1; i++) {

// Get the point close to the Y axis.
yn[0] = min(i, ymax-1);
xn[0] = i - yn[0];

// Get the point close to the X axis.
xn[1] = min(i, xmax-1);
yn[1] = i-xn[1];

// Get the start point due to parity.
int xp = xn[i%2], yp = yn[i%2];

// Get all nodes needed by moving on the diagonal.
do {
ans.push_back(matrix[yp][xp]);
xp += xf [i%2];
yp += yf [i%2];
} while (xp >= 0 && yp >=0 && xp < xmax && yp <ymax);
}
return ans;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: