方法是看评论区想出来的:先将矩阵转置,再将每一行逆转
class Solution {
public:
int n,m,l,k;
struct bian{int u;int v;int d;
};
void digui(int loc,int c[],vector<bian> bi,int now,int q,bool colour[],int& maxx,bool jg[]){if(q>l) return ;if(loc==n-1&&q<=l&&maxx<now){maxx=now;now=0;return ;}else for(int i=0;i<bi.size();i++){if(loc==bi[i].u&&jg[bi[i].v]==0&&colour[c[bi[i].v]]==0){colour[c[bi[i].v]]=1;vector<bian> bia(bi);bia.erase(bia.begin()+i);jg[bi[i].v]=1;digui(bi[i].v,c,bia,now+bi[i].d,q+1,colour,maxx,jg);jg[bi[i].v]=0;colour[c[bi[i].v]]=0;}}if(loc==0) cout<<maxx;
}void rotate(vector<vector<int>>& matrix) {vector<vector<int>> v;int n=matrix.size();for(int j=0;j<n;j++){vector<int> v2;for(int i=0;i<n;i++){vector<int> v1=matrix[i];v2.push_back(v1[j]);}v.push_back(v2);}for(int i=0;i<n;i++) reverse(v[i].begin(),v[i].end());for(int i=0;i<n;i++) matrix[i]=v[i];}
};
也可以一步到位,观察移动位置直接移动(1 1移动到1 n,1 2移动到2 n……2 1移动到1 n-1……以此类推)
代码如下:
class Solution {
public:void rotate(vector<vector<int>>& matrix) {vector<vector<int>> result(matrix);for(int i=0;i<matrix.size();i++){for(int j=0;j<matrix[i].size();j++){vector<int> v(result[j]);vector<int> vv(matrix[i]);v[matrix.size()-i-1]=vv[j];result[j]=v;}}matrix=result;}
};