现有一个NxN的矩阵,阶数为N,请编写一个算法将矩阵顺时针旋转90度并将其作为返回值。要求不使用缓存矩阵,保证N不大于500,元素不大于256,每个元素用int表示。
[[1,2,3],[4,5,6],[7,8,9]],3
返回:[[7,4,1],[8,5,2],[9,6,3]]
public class Transform { public static int[][] transformImage(int[][] mat, int n) { if (mat == null) { return null; } int temp = 0; for(int i=0;i<n-1;i++){ for(int j=0;j<n-i-1;j++){ temp = mat[i][j]; mat[i][j] = mat[n-j-1][n-i-1]; mat[n-j-1][n-i-1] = temp; } } for(int i=0;i<(n/2);++i){ for(int j=0;j<n;++j){ temp = mat[i][j]; mat[i][j] = mat[n-i-1][j]; mat[n-i-1][j] = temp; } } return mat; } }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题