solution.cpp 1019 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<int> spiralOrder(vector<vector<int>> &matrix)
	{
		vector<int> res;
		int hor_top = 0;
		int hor_bottom = matrix.size() - 1;
		int ver_left = 0;
		int ver_right = matrix[0].size() - 1;
		int direction = 0;
		while (hor_top <= hor_bottom && ver_left <= ver_right)
		{
			switch (direction)
			{
			case 0:
				for (int i = ver_left; i <= ver_right; i++)
				{
					res.push_back(matrix[hor_top][i]);
				}
				hor_top++;
				break;
			case 1:
				for (int i = hor_top; i <= hor_bottom; i++)
				{
					res.push_back(matrix[i][ver_right]);
				}
				ver_right--;
				break;
			case 2:
				for (int i = ver_right; i >= ver_left; i--)
				{
					res.push_back(matrix[hor_bottom][i]);
				}
				hor_bottom--;
				break;
			case 3:
				for (int i = hor_bottom; i >= hor_top; i--)
				{
					res.push_back(matrix[i][ver_left]);
				}
				ver_left++;
				break;
			default:
				break;
			}
			direction++;
			direction %= 4;
		}
		return res;
	}
};