集册 Java实例教程 旋转矩阵

旋转矩阵

欢马劈雪     最近更新时间:2020-01-02 10:19:05

495
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
旋转矩阵


public class Main {
/**N  o w  J a v a . c o m**/

  public void rotate(int[][] matrix) {

    if (matrix == null)

      return;

    int N = matrix.length;

    for (int i = 0; i < N / 2; i++) // This is the layer

      for (int j = i; j < N - i - 1; j++) { // This is the offset to start

        // swap

        int t = matrix[i][j];

        matrix[i][j] = matrix[N - j - 1][i];

        matrix[N - j - 1][i] = matrix[N - i - 1][N - j - 1];

        matrix[N - i - 1][N - j - 1] = matrix[j][N - i - 1];

        matrix[j][N - i - 1] = t;

      }

  }


  public static void main(String[] args) {

    int[][] matrix = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 },

        { 21, 22, 23, 24, 25 } };

    for (int i = 0; i < matrix.length; i++) {/** from N  o w  J a v a . c o m**/

      for (int j = 0; j < matrix[0].length; j++)

        System.out.print(matrix[i][j] + " ");

      System.out.print("\n");

    }

    new Main().rotate(matrix);

    System.out.print("\n");

    System.out.print("\n");

    System.out.print("\n");


    
展开阅读全文