Diagonal Traverse

来源:互联网 发布:网络诈骗罪判决书 编辑:程序博客网 时间:2024/05/16 10:14

Diagonal Traverse

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]Output:  [1,2,4,7,5,3,6,8,9]Explanation:

Note:

  1. The total number of elements of the given matrix will not exceed 10,000.
解析: 主要控制好边界点和方向

代码:

class Solution {public:    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {              vector<int>ans;         if (matrix.empty())         return ans;         int M=matrix.size();        int N=matrix[0].size();        int dx[2]={-1,1};        int dy[2]={1,-1};        int dir=1;        int row=0;        int col=0;        for (int i=0; i<M*N; i++)        {            ans.push_back(matrix[row][col]);            row+=dy[dir];            col+=dx[dir];            int flag=0;                       if (col>=N)            {                row+=2;                col=N-1;                flag=1;            }            if (row<0)            {                row=0;                flag=1;                //dir=1-dir;            }                        if (row>=M)            {                row=M-1;                col+=2;                flag=1;            }            if (col<0)            {                col=0;                flag=1;            }            if(flag)            {                dir=1-dir;            }        }        return ans;                    }};






0 0
原创粉丝点击