2016校招真题之顺时针旋转矩阵

1、题目描述

有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于300。

测试样例:
[[1,2,3],[4,5,6],[7,8,9]],3
返回:
[[7,4,1],[8,5,2],[9,6,3]]
 

2、代码实现

 1 package com.wcy.october;
 2 
 3 /**
 4  * 时间:2016年10月16日
 5  * 题目:顺时针旋转矩阵
 6  * 题目描述:有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于300。
 7  * 测试样例:[[1,2,3],[4,5,6],[7,8,9]],3 返回:[[7,4,1],[8,5,2],[9,6,3]]
 8  */
 9 public class Rotate {
10 
11     /**
12      * 方法一:将矩阵顺时针旋转90度
13      * @param mat 需要顺时针旋转90度的矩阵
14      * @param n 矩阵的大小
15      * @return 顺时针旋转90度后的新矩阵
16      */
17     public int[][] rotateMatrix(int[][] mat, int n) {
18         int[][] result = new int[n][n];
19         for (int i = 0; i < mat.length; i++) {
20             int num = 0;
21             for (int j = mat.length-1; j >= 0&&num < mat.length; j--,num++) {
22                 result[i][num] = mat[j][i];
23             }
24         }
25         return result;
26     }
27     
28     /**
29      * 方法二:将矩阵顺时针旋转90度,找规律:mat[i][j]被旋转到了mat[j][n-i-1]的位置
30      * @param mat 需要顺时针旋转90度的矩阵
31      * @param n 矩阵的大小
32      * @return 顺时针旋转90度后的新矩阵
33      */
34     public int[][] rotateMatrix2(int[][] mat, int n) {
35         int[][] result = new int[n][n];
36         for (int i = 0; i < mat.length; i++) {
37             for (int j = 0; j < mat.length; j++) {
38                 result[j][n-i-1] = mat[i][j];
39             }
40         }
41         return result;
42     }
43     
44     /**
45      * 用户页面测试
46      * @param args
47      */
48     public static void main(String[] args) {
49         Rotate rotate = new Rotate();
50         int[][] mat = {{1,2,3,5,6},{7,8,9,10,11},{12,13,14,15,16},{17,18,19,20,21},{22,23,24,25,26}};
51         int n = mat.length;
52         int[][] result = rotate.rotateMatrix(mat, n);
53         // 打印出结果
54         for (int i = 0; i < result.length; i++) {
55             for (int j = 0; j < result.length; j++) {
56                 if (j != result.length-1) {
57                     System.out.print(result[i][j] + " ");
58                 }else {
59                     System.out.print(result[i][j]);
60                 }
61             }
62             System.out.println();
63         }
64     }
65 }
原文地址:https://www.cnblogs.com/wangchaoyuan/p/5968658.html