Topic
将正方形矩阵顺时针转动90
Java code
Package com.lizhouwei.chapter8;/** * @Description: Rotates the square matrix clockwise * @Author: Lizhouwei * @CreateDate: 2018/4/28 22:16 * @Mo Dify 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; }}//test 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 + +) {Sys Tem.out.print (matrix[i][j]+ ""); } System.out.println (); } }}
Results
Code interview guide for programmers eighth array and matrix problems turn the square matrix clockwise 90