码迷,mamicode.com
首页 > 编程语言 > 详细

《程序员代码面试指南》第八章 数组和矩阵问题 将正方形矩阵顺时针转动90

时间:2018-04-28 23:43:18      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:time   for   ota   oid   技术   static   分享图片   面试   length   

题目

将正方形矩阵顺时针转动90

java代码

package com.lizhouwei.chapter8;

/**
 * @Description: 将正方形矩阵顺时针转动90
 * @Author: lizhouwei
 * @CreateDate: 2018/4/28 22:16
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_2 {
    public void rotate(int[][] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        while (tR < dR) {
            rotateEdge(matrix, tR++, dR--, tC++, dC--);
        }
    }

    public void rotateEdge(int[][] matrix, int tR, int dR, int tC, int dC) {
        int times = dC - tC;
        int temp = 0;
        for (int i = 0; i < times; i++) {
            temp = matrix[tR][tC + i];
            matrix[tR][tC + i] = matrix[dR - i][tC];
            matrix[dR - i][tC] = matrix[dR][dC - i];
            matrix[dR][dC - i] = matrix[tR + i][dC];
            matrix[tR + i][dC] = temp;
        }
    }

    //测试
    public static void main(String[] args) {
        Chapter8_2 chapter = new Chapter8_2();
        int[][] matrix = {{1, 2, 3, 4}, {5,6,7,8}, {9, 10, 11, 12}, {13, 14, 15, 16 }};
        chapter.rotate(matrix);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j]+" ");
            }
            System.out.println( );
        }
    }
}

结果

技术分享图片

《程序员代码面试指南》第八章 数组和矩阵问题 将正方形矩阵顺时针转动90

标签:time   for   ota   oid   技术   static   分享图片   面试   length   

原文地址:https://www.cnblogs.com/lizhouwei/p/8969859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!