59. Spiral Matrix II的C++解法

和 Spiral Matrix I用了一个方法,遇到边界和赋过值的地方就拐弯。但是速度比较慢。
 

 class Solution {
 public:
	 vector<vector<int>> generateMatrix(int n) {
		 vector<vector<int>> res(n, vector<int>(n));
		 if (n == 0) return res;
		 vector<vector<int>> direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
		 int step =0 ;
		 int count = 1;
		 int x = 0;
		 int y = 0;
		 res[x][y] = count;
		 while (count < n*n)
		 {
			 while ((x + direct[step][0] >= 0) && (x + direct[step][0] < n) && (y + direct[step][1] >= 0) && (y + direct[step][1] < n) && (res[x + direct[step][0]][y + direct[step][1]] == 0) && (count <= n*n))
			 {
				 x = x + direct[step][0];
				 y = y + direct[step][1];
				 count++;
				 res[x][y] = count;
			 }
			 step = (step + 1) % 4;
		 }
		 return res;
	 }
 };

最快的还是记录步长转圈的:
i记录的是转了第几圈,j是变动的那个坐标。这个方法是找到每一圈长度和圈数的关系。

class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > ret( n, vector<int>(n) );
        	int k = 1, i = 0;
        	while( k <= n * n )
        	{
        		int j = i;
                    // four steps
        		while( j < n - i )             // 1. horizonal, left to right
        			ret[i][j++] = k++;
        		j = i + 1;
        		while( j < n - i )             // 2. vertical, top to bottom
        			ret[j++][n-i-1] = k++;
        		j = n - i - 2;
        		while( j > i )                  // 3. horizonal, right to left 
        			ret[n-i-1][j--] = k++;
        		j = n - i - 1;
        		while( j > i )                  // 4. vertical, bottom to  top 
        			ret[j--][i] = k++;
        		i++;      // next loop
        	}
        	return ret;
        }
    };

相关问题:
54. Spiral Matrix的C++解法
885. Spiral Matrix III的C++解法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值