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.
*/
/*
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; } };
相关文章推荐
- leetcode 498. Diagonal Traverse
- LeetCode: 498. Diagonal Traverse
- LeetCode 498. Diagonal Traverse
- LeetCode - 498. Diagonal Traverse
- LeetCode "498. Diagonal Traverse"
- leetcode 498. Diagonal Traverse 矩阵对角遍历 + 控制方向即可
- [leetcode]498. Diagonal Traverse
- leetcode_498. Diagonal Traverse ? 待解决
- LeetCode笔记:498. Diagonal Traverse
- [LeetCode]498. Diagonal Traverse
- [leetcode] 498. Diagonal Traverse -- JavaScript 代码
- [LeetCode] Diagonal Traverse 对角线遍历
- 498. Diagonal Traverse
- LeetCode之levelTraverse
- [Leetcode] Postorder Traverse of Binary Tree
- LeetCode之levelTraverse
- 【Leetcode】238-Product of Array Except Self【Java实现】【Medium】【two way traverse】
- 498. Diagonal Traverse
- [每日一题]498. Diagonal Traverse
- 498. Diagonal Traverse