给定一个n*n的矩阵matrix,请把这个矩阵顺时针转动90度。
输入包含多行,第一行一个整数n,代表矩阵的行数和列数,接下来n行,每行n个整数,代表矩阵matrix。
输出旋转后的矩阵(包含n行,每行n个数)。
4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4
额外空间复杂度。
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); String[][] arr = new String[n][n]; for(int i=0;i<n;i++){ arr[i] = br.readLine().trim().split(" "); } rotate(arr); StringBuilder sb = new StringBuilder(); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ sb.append(arr[i][j]).append(" "); } sb.append("\n"); } System.out.print(sb.toString()); } private static void rotate(String[][] arr){ if(arr==null||arr.length<1) return; int tr=0; int tc=0; int dr=arr.length-1; int dc = arr[0].length-1; while(tr<=dr&&tc<=dc){ rotateEdge(arr,tr++,tc++,dr--,dc--); } } private static void rotateEdge(String[][] arr,int tr,int tc,int dr,int dc){ int t = dc-tc; String temp; for(int i=0;i<t;i++){ temp = arr[tr][tc+i]; arr[tr][tc+i] = arr[dr-i][tc]; arr[dr-i][tc] = arr[dr][dc-i]; arr[dr][dc-i] = arr[tr+i][dc]; arr[tr+i][dc] = temp; } } }
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); int[][] two = new int[n][n]; for(int i = 0; i < n; i++){ String s = sc.nextLine(); String[] ss = s.split(" "); for(int j = 0; j < n; j++){ two[i][j] = Integer.parseInt(ss[j]); } } int[][] one = new int[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ System.out.print(two[n-j-1][i]+" "); } System.out.println(); } } }
import java.util.Scanner; public class Main { public static 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++, tC++, dR--, dC--); } } public static void rotateEdge(int[][] matrix, int tR, int tC, int dR, int dC) { int times = dR - tR; for (int i = 0; i < times; i++) { int 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 printMatrix(int[][] 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(); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] matrix = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] =sc.nextInt(); } } rotate(matrix); printMatrix(matrix); } }