順時針旋轉,從上圖中不難看出行列進行了變換。因為這是一道暴力可以解決的問題,我們直接嘗試使用行列轉換看能不能得到想要的結果。
public static void main(String[] args) {Scanner scan = new Scanner(System.in);int n=scan.nextInt();int m=scan.nextInt();int count=0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {arr[i][j]=scan.nextInt();}}for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {System.out.print(arr[j][i]+" ");}System.out.println();}scan.close();}
如上圖所示我們將行列直接轉換,但是我們會得到如下的示例結果。由于在進行行列轉換的時候,將預先的3行變成4列,4列變成三行超出了原來的數組長度導致了出現0并且轉換錯誤的情況。接下來我們觀察一下順時針轉換的下標的位置變化規律可以發現1 3 5 7由原來的第一行(0,0)~(0,3)轉換為第三列(0,2)~(3,2),我們不難發現坐標在原來的基礎上實現的是行遞增,列不變。
3 4
1 3 5 7
9 8 7 6
3 5 9 7
1 9 3 0
3 8 5 0
5 7 9 0
代碼實現👇
public static void main(String[] args) {Scanner scan = new Scanner(System.in);int n=scan.nextInt();int m=scan.nextInt();int count=0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {arr[i][j]=scan.nextInt();}}for (int i = 0; i < m; i++) {//行變為列的大小for (int j = n-1; j >= 0; j--) {//列每次按原來的行遞減輸出System.out.print(arr[j][i]+" ");}System.out.println();}scan.close();}
大家多動手,比較簡單