498. Diagonal Traverse

class Solution
{
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) 
    {
        if(matrix.empty())
        {
            return {};
        }
		vector<int> result;
		bool fromUp = false;  /* false 自下而上 ture 自上而下*/

		int a = 0;
		int b = 0;  //(a,b)  A点

		int c = 0;
		int d = 0;  //(c,d) B点

		int endR = matrix.size() - 1;
		int endC = matrix[0].size() - 1;

       
		while (a != endR + 1)  //a 走到最后一行的时候b到了最后一列
		{
			this->printLevel(matrix,a,b,c,d,fromUp,result);
			a = (b == endC ? a + 1 : a);
			b = (b == endC ? b : b + 1);
			d = (c == endR ? d + 1 : d);
			c = (c == endR ? c : c + 1);


			fromUp = !fromUp;
		}
		return result;
    }
private:
    	/*打印一列*/
	void printLevel(vector<vector<int>>& matrix,int a,int b,int c,int d,bool f,vector<int>& result)
	{
		if (f)
		{
			/*f = true 自上而下的打印矩阵*/
			while (a != c + 1)
			{
				result.push_back(matrix[a][b]);
				a++;
				b--;
			}
		}
		else
		{
			/*f = false 自下而上的打印矩阵*/
			while (c != a - 1)
			{
				result.push_back(matrix[c][d]);
				c--;
				d++;
			}
		}
	}
};
posted @ 2019-12-19 20:23  尚修能的技术博客  阅读(133)  评论(0编辑  收藏  举报