旋转的矩阵-数据结构
题目描述
给定一个n*m的矩阵,请以顺、逆时针交替旋转的方式打印出每个元素。
Input Format
第一行n m; 0<n,m<100
后n行,每行m个整数。
Output Format
n*m个矩阵元素,空格隔开。
Example
Input
4 4
1 2 3 4
12 13 16 5
11 14 15 6
10 9 8 7
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Input
3 4
1 2 3 4
10 11 12 5
9 8 7 6
Output
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int m, n;
while(cin >> m >> n)
{
vector<vector<int>> res(m, vector<int>(n));
for(int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++) cin >> res[i][j];
}
int row = res.size();
int col = res[0].size();
int left = 0, right = col-1, top = 0, bottom = row-1;
vector<int> s;
while(left <= right && top <= bottom)
{
/*顺时针*/
for(int i = left; i <= right; i++) s.push_back(res[top][i]);
for(int i = top + 1; i <= bottom; i++) s.push_back(res[i][right]);
if(top != bottom)
{
for(int i = right - 1; i >= left; i--) s.push_back(res[bottom][i]);
}
if(left != right)
{
for(int i = bottom - 1;i >= top + 1 ; i--) s.push_back(res[i][left]);
}
left++, top++, right--, bottom--;
/*当矩阵较大,能够绕完顺时针后再逆时针绕圈时,
以下为逆时针录入情况*/
if(left < right && top < bottom)
{
for(int i = top; i <= bottom ; i++) s.push_back(res[i][left]);
for(int i = left + 1; i <= right ; i++) s.push_back(res[right-1][i]);
if(left != right)
{
for(int i = bottom - 1; i >= top; i--) s.push_back(res[i][right]);
}
if(top != bottom)
{
for(int i = right - 1; i >= left + 1; i--) s.push_back(res[top][i]);
}
left++, top++, right--, bottom--;
}
}
for(int i = 0; i < s.size(); i++)
{
if (i == s.size() - 1)
cout << s[i] << endl;
else
cout << s[i] << ' ';
}
}
return 0;
}