leetcode--------Spiral Matrix

本文介绍了一种螺旋遍历二维矩阵的算法实现,通过控制边界条件,实现了从外层向内层螺旋打印矩阵元素的功能。特别针对单列情况进行了额外处理,确保了算法的完整性和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依次打印外层,然后打印里层;

 

当处理里层的边界问题时,比如只有一列时,出现了一点问题,于是就多了几句判断条件

class Solution {

    
public:

	void c_clock_wise(vector<int> &_print, vector<vector<int>>& matrix, int lo_row, int lo_col, int hi_row, int hi_col,int &cur)
	{
		int C = matrix[0].size();
		int my_row = lo_row;
		int my_col = lo_col;
		if(lo_row<hi_row&&lo_col<hi_col)
		{ 
		while (my_col < hi_col)
		{
			_print[cur++] = matrix[my_row][my_col];
			my_col++;
		}
		while (my_row < hi_row)
		{
			_print[cur++] = matrix[my_row][my_col];
			my_row++;
		}
		while (my_col > lo_col)
		{
			_print[cur++] = matrix[my_row][my_col];
			my_col--;
		}
		while (my_row > lo_row)
		{
			_print[cur++] = matrix[my_row][my_col];
			my_row--;
		}
		}
		else
		{
			while (my_col <= hi_col)
			{
				_print[cur++] = matrix[my_row][my_col];
				my_col++;
			}
            my_col--;
			my_row++;
            while (my_row <= hi_row)
		    {
			    _print[cur++] = matrix[my_row][my_col];
			    my_row++;
		    }
		}

	}

	vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty())  return vector<int>();
		int R = matrix.size();
		int C = matrix[0].size();
		vector<int> _pp(R*C);
		int c = 0, r = 0;
		int cur = 0;
		while ((c < C--) && (r < R--))
		{
			c_clock_wise(_pp, matrix, r, c, R, C,cur);
			++c, ++r;
		}
		return _pp;


	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值