LeetCode Spiral Matrix

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
    	vector<int> ret;
		int m = matrix.size();
		if(m > 0)
		{
			int n = matrix[0].size();
			if(n > 0)
			{
				for(int layer = 0; layer < min(m, n)/2; ++layer)
				{
					for(int i = layer; i < n-1-layer; ++i)
						ret.push_back(matrix[layer][i]);
					for(int i = layer; i < m-1-layer; ++i)
						ret.push_back(matrix[i][n-1-layer]);
					for(int i = n-1-layer; i > layer; --i)
						ret.push_back(matrix[m-1-layer][i]);
					for(int i = m-1-layer; i > layer; --i)
						ret.push_back(matrix[i][layer]);
				}
				int layer = min(m, n)/2;
				if(1 == min(m, n)%2)
				{
					if(m > n)
					{
						for(int i = layer; i <= m-1-layer; ++i)
							ret.push_back(matrix[i][n/2]);
					}
					else
					{
						for(int i = layer; i <= n-1-layer; ++i)
							ret.push_back(matrix[m/2][i]);
					}
				}
			}
		}
		return ret;
    }
};



你可能感兴趣的:(Matrix,layer)