【数据结构和算法】顺时针旋转矩阵
顺时针旋转矩阵
http://www.nowcoder.com/practice/2e95333fbdd4451395066957e24909cc
先上下交换,在对角线交换
这题是让把矩阵顺时针旋转90度,最简单的一种方式就是先上下关于中心线翻转,然后再对角线翻转,具体看下图形分析
原理比较简单,来直接看下代码
public int[][] rotateMatrix(int[][] matrix, int n) {
int length = matrix.length;
//先上下交换
for (int i = 0; i < length / 2; i++) {
int temp[] = matrix[i];
matrix[i] = matrix[length - i - 1];
matrix[length - i - 1] = temp;
}
//在按照对角线交换
for (int i = 0; i < length; ++i) {
for (int j = i + 1; j < length; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return matrix;
}
如果觉得有用就给个赞吧,还可以关注我的《牛客博客》查看更多的详细题解
数据结构和算法 文章被收录于专栏
专注于算法题的讲解,包含常见数据结构,排序,查找,动态规划,回溯算法,贪心算法,双指针,BFS和DFS等等。