Leetcode 498. Diagonal Traverse
// 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; } };