leetcode_54题——Spiral Matrix(数组)

Spiral Matrix

  Total Accepted: 31249 Total Submissions: 150428My Submissions

 

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].

 

Hide Tags
  Array
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

      这道题主要是还和第59题差不多,就是对数组螺旋的读,在这中间只要注意好读取时的边界条件,还有这个数组不一定是n*n的

#include<iostream>

#include<vector>

using namespace std;



vector<int> spiralOrder(vector<vector<int>>& matrix) {

	vector<int> last_vec;

	if(matrix.empty())

		return last_vec;



	int n=matrix.size();

	int m=matrix[0].size();



	if(n==1)

	{

		for(int i=0;i<m;i++)

			last_vec.push_back(matrix[0][i]);

		return last_vec;

	}



	if(m==1)

	{

		for(int j=0;j<n;j++)

			last_vec.push_back(matrix[j][0]);

		return last_vec;

	}



	int quan1=n;

	int quan2=m;

	int x1=0,x2=0;

	int y1=0,y2=m-1;

	int m1=n-1,m2=m-1;

	int n1=n-1,n2=0;

	while(quan1>0&&quan2>0)

	{

		if(quan2>=2)

			for(int i=x2;i<=x2+(quan2-2);i++)

				last_vec.push_back(matrix[x1][i]);

		if(quan1>=2)

			for(int i=y1;i<=y1+(quan1-2);i++)

				last_vec.push_back(matrix[i][y2]);

		if(quan2>=2)

			for(int i=m2;i>=m2-(quan2-2);i--)

				last_vec.push_back(matrix[m1][i]);

		if(quan1>=2)

			for(int i=n1;i>=n1-(quan1-2);i--)

				last_vec.push_back(matrix[i][n2]);

		quan1-=2;

		quan2-=2;

		x1++;x2++;

		y1++;y2--;

		m1--;m2--;

		n1--;n2++;



		if(quan1==1&&quan2==1)

			last_vec.push_back(matrix[x1][x2]);

	}

	return last_vec;

}



int main()

{

	vector<vector<int> > vec;

	vector<int> vec1;

}

  

你可能感兴趣的:(LeetCode)