54. Spiral Matrix的C++解法

本来还是想用步长来决定多久转一圈,但是发现最终的结束条件没有想象得那么好控制,写起来也麻烦。于是新想了一个算法,走到边界或者已经走过的地方就拐弯。代码投机取巧了一下,直接在原矩阵上把走过的改为-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++解法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值