方法是网上找的
一开始我想的好复杂,一圈圈的记录vector,然后改变顺序再赋值
结果!!!!
记录个pre 和 cur 就好了,还是原地的
思路啊思路啊
不过还是有陷阱就是,若是没处理以行/列,不改变值得话,那么交叉位置每个顶角会重复访问
啊 好久不看c++,好多都忘记了
/*
Rotate Matrix.
Given a matrix, clockwise rotate elements in it.
Example:
Input
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6
For 4*4 matrix
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
*/
#include <stdlib.h>
#include<iostream>
#include<vector>
#include<sstream>
#include <string>
using namespace std;
//&这里是引用!!不是地址
void getmatrix(vector<vector<int> >& matrix)
{
string str, line;
while(getline(cin, line))//读一行直到ctrl+z结束,全部数据存到line里面
{
vector<int> rows;
istringstream stream(line);//这个就把一行数据按空格分开了一个个string
while(stream>>str)
rows.push_back(atoi(str.c_str()));//string转成int,放到一个vector里,一行
matrix.push_back(rows);//把这一行放到另外一个vector里
//cout<<matrix.size()<<endl;
}
}
//旋转矩阵
/*
每次处理相当于处理这样一个矩阵
(row,col) ..... (row,n)
. (row+1,col+1) .
. .
. (m-1,n-1) .
(m,col) ..... (m,m)
下一次就是缩小范围
row+1
col+1
m-1
n-1
*/
void rotatematrix(vector<vector<int> >& matrix)
{
int m = matrix.size();//行数,
int n = matrix[0].size();//列数,结束(m,n)
int row = 0;//起始坐标(row,col)
int col = 0;//起始
while(row<m&&col<n)//
{
if(row + 1 == m || col + 1 == n)//只剩一行或者一列
break;
int pre = matrix[row + 1][col];
int cur;
for(int k = col;k<n;k++)//从左往右,行row不变,列加1从col到n
{
cur = matrix[row][k];
matrix[row][k]=pre;
pre = cur;
}
row++;//第一行处理完毕
for(int k = row;k<m;k++)//从上往下,列n不变,行加1从row+1到m
{
cur = matrix[k][n-1];
matrix[k][n-1]=pre;
pre = cur;
}
n--;//最后一列处理完毕
for(int k = n-1;k>=col;k--)//从右往左,行m不变,列减1从n-1到col
{
cur = matrix[m-1][k];
matrix[m-1][k]=pre;
pre=cur;
}
m--;//最后一行处理完毕
for(int k =m-1;k>=row;k--)//从下往上,列col不变,行减1从m-1到row
{
cur = matrix[k][col];
matrix[k][col]=pre;
pre=cur;
}
col++;//第一列处理完毕
}
}
//打印矩阵
void printmatrix(vector<vector<int> >& matrix)
{
for(int i = 0; i < matrix.size(); ++i)
{
for(int j=0; j < matrix[i].size(); j++)
cout << matrix[i][j] << " ";
cout<<endl;
}
}
int main()
{
vector<vector<int> > matrix;
getmatrix(matrix);
//printmatrix(matrix);
rotatematrix(matrix);
printmatrix(matrix);
//cout<<matrix.size()<<endl; 行数
//cout<<matrix[0].size()<<endl; 列数
return 0;
}