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

时间:2022-07-20 04:36:27
1. 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].

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<vector<int>> m = { { 1, 2,3 }, { 2, 3 ,4}, { 4, 5 ,5} };
	cout << m.size() << "  " << m[0].size() << endl;
	//进行螺旋输出
	int x1 = 0, y1 = 0;
	int x2 = m.size() - 1;
	int y2 = m[0].size() - 1;
	vector<int>r;
	while (x1 <= x2 && y1 <= y2)
	{
		//对上面的一层进行处理
		for (int y = y1; y <= y2; y++)
			r.push_back(m[x1][y]);
		//对右边进行处理
		for (int x = x1 + 1; x <= x2; x++)
			r.push_back(m[x][y2]);
		//对下面的进行处理
		for (int y = y2 - 1; y > y1; --y)
			r.push_back(m[x2][y]);
		for (int x = x2 - 1; x > x1; x--)
			r.push_back(m[x][y1]);
		x1++; y1++; x2--; y2--;
	}
	for (size_t i = 0; i < r.size(); i++)
		cout << r[i] << endl;
	system("pause");
	return 0;
}