问题描述:
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:
问题分析:
以横纵坐标为准线,将对应的值保存到结果集中去。
过程详见代码:
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
vector<int> res;
int m = matrix.size();
if (!m) return res;
int n = matrix[0].size(), flag = 0;// flag = 0表示斜向上,flag = 1表示斜向下
int i = 1, j = -1,num = m * n,t = 0;
res.resize(num);
while (t < num)
{
if (!flag)
{
if (isGood(i - 1, j + 1, m, n))
{
res[t] = (matrix[--i][++j]);
}
else
{
if (j + 1 < n)
{
res[t] = (matrix[i][++j]);
}
else if (i + 1 < m)
{
res[t] = (matrix[++i][j]);
}
flag = 1;
}
}
else
{
if (isGood(i + 1, j - 1, m, n))
{
res[t] = (matrix[++i][--j]);
}
else
{
if (i + 1 < m)
{
res[t] = (matrix[++i][j]);
}
else if (j + 1 < n)
{
res[t] = (matrix[i][++j]);
}
flag = 0;
}
}
t++;
}
return res;
}
bool isGood(int i, int j, int m ,int n)
{
return i < m && i >= 0 && j < n && j >= 0;
}
};