输入有多组数据。 每组数据第一行输入n(1<=n<=9),从第二行开始输入两个n阶矩阵。
判断第二个是否是第一个的旋转矩阵,如果是,输出旋转角度(0、90、180、270),如果不是,输出-1。 如果旋转角度的结果有多个,则输出最小的那个。
3 1 2 3 4 5 6 7 8 9 7 4 1 8 5 2 9 6 3
90
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { int n = scanner.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arr[i][j] = scanner.nextInt(); } } //旋转90度 int[][] arr90 = new int[n][n]; for (int i = 0; i < arr90.length; i++) { for (int j = 0; j < arr90[i].length; j++) { arr90[i][j] = arr[n-j-1][i]; } } int[][] arr180 = new int[n][n]; for (int i = 0; i < arr180.length; i++) { for (int j = 0; j < arr180[i].length; j++) { arr180[i][j] = arr90[n-j-1][i]; } } int[][] arr270 = new int[n][n]; for (int i = 0; i < arr270.length; i++) { for (int j = 0; j < arr270[i].length; j++) { arr270[i][j] = arr180[n-j-1][i]; } } int[][] arrLast = new int[n][n]; for (int i = 0; i < arrLast.length; i++) { for (int j = 0; j < arrLast[i].length; j++) { arrLast[i][j] = scanner.nextInt(); } } if (isEqual(arrLast, arr)) { System.out.println(0); }else if (isEqual(arrLast, arr90)) { System.out.println(90); }else if (isEqual(arrLast, arr180)) { System.out.println(180); }else if (isEqual(arrLast, arr270)) { System.out.println(270); }else { System.out.println(-1); } } } public static boolean isEqual(int[][] arr,int[][] arr2) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] != arr2[i][j]) { return false; } } } return true; } }
package beihang; import java.util.Scanner; /*航计算机历年复试上机题 矩阵旋转 链接:https://www.nowcoder.com/practice/bd62095a03a545729cdbfc506e0da952? tpId=66&tqId=29632&rp=0&ru=/kaoyan/retest/1004&qru=/ta/buaa-kaoyan/question-ranking*/ public class Three { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[][] = new int[n][n]; int b[][] = new int[n][n]; for (int i=0;i<n;++i){ for (int j=0;j<n;++j) a[i][j] = sc.nextInt(); } for (int i=0;i<n;++i){ for (int j=0;j<n;++j) b[i][j] = sc.nextInt(); } int ans = -1; if (ans == -1 && turn(a,b,0)) ans = 0; if (ans == -1 && turn(a,b,90)) ans = 90; if (ans == -1 && turn(a,b,180)) ans = 180; if (ans == -1 && turn(a,b,270)) ans = 270; System.out.println(ans); sc.close(); } //c是旋转的角度,该方法是判断b是否是a旋转c角度得到的,是返回true,否返回false private static boolean turn(int[][] a, int[][] b,int c) { int n = a.length; for (int i=0;i<n;++i){ for (int j=0;j<n;++j){ int row=0,col=0; switch(c){ case 0: row = i; col = j; break; case 90: row = j; col = n-i-1; break; case 180: row = n-i-1; col = n-j-1; break; case 270: row = n-j-1; col = i; break; } if (a[i][j] != b[row][col]) return false; } } return true; } }