Spiral Matrix

难度:1

1Y又失败。。

解法:模拟。。

class Solution 
{
public:
	const int LEFT=0;
	const int RIGHT=1;
	const int DOWN=2;
	const int UP=3;
    vector<int> spiralOrder(vector<vector<int> > &matrix) 
	{
		vector<int>ans;
		if(matrix.size() == 0)	return ans;
		if(matrix.size() == 1)	return matrix[0];
		if(matrix[0].size() == 0)	return ans;
		int m=matrix.size();//row
		int n=matrix[0].size();//col
		int cur_x=0,cur_y=0,cur_dir=RIGHT;
		ans.push_back(matrix[cur_x][cur_y]);
		int border_left=0;
		int border_right=n-1;
		int border_down=m-1;
		int border_up=0;
		while(border_left<=border_right&&border_up<=border_down)
		{
			if(cur_x == border_up && cur_x == border_down && cur_y == border_left && cur_y == border_right)
			{
				break;
			}
			int next_x,next_y;
			if(cur_dir == LEFT)
			{
				next_x=cur_x;
				next_y=cur_y-1;
				if(next_y < border_left)		
				{
					cur_dir=UP;
					border_down--;
					continue;
				}
			}
			else if(cur_dir == RIGHT)
			{
				next_x=cur_x;
				next_y=cur_y+1;
				if(next_y>border_right)
				{
					cur_dir=DOWN;
					border_up++;
					continue;
				}
			}
			else if(cur_dir == DOWN)
			{
				next_x=cur_x+1;
				next_y=cur_y;
				if(next_x>border_down)
				{
					cur_dir=LEFT;
					border_right--;
					continue;
				}
			}
			else
			{
				next_x=cur_x-1;
				next_y=cur_y;
				if(next_x<border_up)
				{
					cur_dir=RIGHT;
					border_left++;
					continue;
				}
			}
			ans.push_back(matrix[next_x][next_y]);
			cur_x=next_x;
			cur_y=next_y;
		}
		return ans;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值