题目描述
对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。
给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。
测试样例:
[[1,2],[3,4]],2,2
返回:[1,2,4,3]
简单的方位替换,可以通过分析和归纳得出:[i][n-1-j]——>[n-1-j][n-1-i]
public class Rotate {
public int[][] rotateMatrix(int[][] mat, int n) {
// write code here
int[][] b = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
b[n-1-j][n-1-i] = mat[i][n-1-j];
}
}
return b;
}
}
上述代码牛客网测试通过,另外还有效率更高的算法,使用分层,由外至内,显然下面代码效率更高
<pre name="code" class="java"> public static void rotate(char a[][],int N)
{
int layer;
for(layer=0; layer<N/2; layer++)
{
int first = layer;
int last = N-1-layer;
int i;
for(i=layer; i<last; i++)
{
int offset = i-layer;
char top = a[first][i];
a[first][i] = a[last-offset][first];
a[last-offset][first] = a[last][last-offset];
a[last][last-offset] = a[i][last];
a[i][last] = top;
}
}
}