Spiral Matrix II


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:
    void leftToRight(vector< vector<int> > &matrix, int left,int right,int row,vector<int> &result)
    {
    	for(int i = left;i <= right;i ++)
			result.push_back(matrix[row][i]);
	}

	void lowToHigh(vector< vector<int> > &matrix, int low,int high , int col,vector<int> &result)
	{
		for(int i = low;i <= high;i ++)
			result.push_back(matrix[i][col]);

	}
    
	void rightToLeft(vector<vector<int> > &matrix, int right,int left, int row,vector<int> &result)
	{
		for(int i = right; i >= left; i --)
			result.push_back(matrix[row][i]);
	}

	void highToLow(vector<vector<int> > &matrix ,int high , int low, int col, vector<int> &result)
	{
		for(int i = high;i >= low;i --)
			result.push_back(matrix[i][col]);
	}


    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		vector<int> result;
		int height = matrix.size();		
		if(height == 0 )
			return result;
		int length = matrix[0].size();
		int left = 0 , right = length - 1, low = 0 , high = height - 1;

		while(left <= right && low <= high)
		{
		if(left <= right && low <= high)
		{
		    leftToRight(matrix,left,right,low,result);
			low ++;
		}
		if(left <= right && low <= high)
		{
		    lowToHigh(matrix,low,high,right,result);
			right --;
		}
		if(left <= right && low <= high)
		{
		    rightToLeft(matrix,right,left,high,result);
			high --;
		}
		if(left <= right && low <= high)
		{
	    	highToLow(matrix,high,low,left,result);
			left ++;
		}
		}
		return result;
        
    }
};

你可能感兴趣的:(Spiral Matrix II)