zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    

      

  • 相关阅读:
    怎样解决:未找到路径“……”的控制器或该控制器未实现 IController?
    错误:org.springframework.jdbc.support.SQLErrorCodesFactory
    springbean的生命周期
    注解到处excel
    nio读取文件,输出文件
    AtomicReference
    唯一id
    hashmap1.7的死锁模拟
    数组模拟stack
    环形队列
  • 原文地址:https://www.cnblogs.com/kkrisen/p/7859856.html
Copyright © 2011-2022 走看看