54. Spiral Matrix的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/82886061

本来还是想用步长来决定多久转一圈,但是发现最终的结束条件没有想象得那么好控制,写起来也麻烦。于是新想了一个算法,走到边界或者已经走过的地方就拐弯。代码投机取巧了一下,直接在原矩阵上把走过的改为-100(测试数据里没有这个值),稳妥的话应该另外建一个数组记录。

 class Solution {
 public:
	 vector<int> spiralOrder(vector<vector<int>>& matrix)  {
		 vector<int> res;
		 if (matrix.empty()) return res;
		 int m = matrix.size();
		 int n = matrix[0].size();
		 vector<vector<int>> direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
		 int step = 0;
		 int x = 0; int y = 0;
		 res.push_back(matrix[x][y]);
		 matrix[x][y] = -100;
		 while (res.size()<matrix.size()*matrix[0].size())
		 {
			 while ((x + direct[step][0] >= 0) && (x + direct[step][0]<m) && (y + direct[step][1] >= 0) && (y + direct[step][1]<n) && (matrix[x + direct[step][0]][y + direct[step][1]] !=-100) && (res.size()<matrix.size()*matrix[0].size()))
			 {
				 x = x + direct[step][0];
				 y = y + direct[step][1];
				 res.push_back(matrix[x][y]);
				 matrix[x][y] = -100;
			 }
			 step = (step + 1) % 4;
		 }
		 return res;
	 }
 };

相关题目:
59. Spiral Matrix II的C++解法​​​​​​​
885. Spiral Matrix III的C++解法

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/82886061