1. 程式人生 > >498.對角線遍歷

498.對角線遍歷

498.對角線遍歷

將集中特殊情況打印出來,最後解決其他情況;

 

 

class Solution {
public:
	vector<int> findDiagonalOrder(vector<vector<int>>& matrix) 
	{
		vector<int> ans;
		if (matrix.empty())
		{
			return ans;
		}
		int m = matrix.size(), n = matrix[0].size();
		int i = 0, j = 0;
		bool confine = 0;
		if (m==1)
		{
			return matrix[0];
		}
		if (n==1)
		{
			for (int k = 0; k < m; k++)
			{
				ans.push_back(matrix[k][0]);
			}
			return ans;
		}
		while (i < m&&j < n)
		{
			ans.push_back(matrix[i][j]);
			dis(ans);

			 if ((i+j)%2==0)
			 {
				 if (i == 0 && j != n - 1)
					 j++;
				 else if (i != 0 && j == n - 1)
					 i++;
				 else if (i == 0 && j == n - 1)
					 i++;
				 else
					 i--, j++;
			 }
			 else
			 {
				 if (j == 0 && i != m - 1)
					 i++;
				 else if (i == m - 1 && j != 0)
					 j++;
				 else if (i == m - 1 && j == 0)
					 j++;
				 else
					 i++, j--;
			 }

		}
		//ans.push_back(matrix[m][n]);
		//dis(ans);
		return ans;
	}
	void dis(vector<int>s)
	{
		for (int i = 0; i < s.size(); i++)
		{
			cout << s[i] << " ";
		}
		cout << endl;
	}
};