用 Java 編寫程式,將矩陣逆時針旋轉 90 度


假設我們給定一個 N×N 的方陣。任務是逆時針旋轉該矩陣。例如,

輸入-1

N = 3
matrix[ ][ ] = [
   [1 2 3],
   [4 5 6],
   [7 8 9]
]

輸出

3 6 9 2 5 8 1 4 7


說明:逆時針旋轉矩陣後,將生成以下輸出:3 6 9 2 5 8 1 4 7。

解決此問題的思路

最初的想法是找到給定矩陣的轉置,然後行序遍歷時交換矩陣的每個元素。

  • 輸入一個方陣。

  • 求矩陣的轉置。

  • 將索引為 0 的元素與索引為 n-1 的元素交換。

  • 返回輸出。

示例

import java.io.*;
class Solution {
   static void rotateMatrix(
      int n, int matrix[][]){
         for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
               int temp= matrix[i][j];
               matrix[i][j]= matrix[j][i];
               matrix[j][i]= temp;
            }
         }
   for(int i=0;i<n;i++){
      int top=0;
      int bottom = n-1;
      while(top<bottom){
         int temp = matrix[top][i];
         matrix[top][i]=matrix[bottom][i];
         matrix[bottom][i] = temp;
         top++;
         bottom--;
      }
   }
}
static void displayMatrix(int N, int mat[][]){
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++)
         System.out.print(" " + mat[i][j]);
         System.out.print("\n");
      }
      System.out.print("\n");
   }
   public static void main(String[] args){
      int N = 3;
      int mat[][] = {
         {1,2,3},
         {4,5,6},
         {7,8,9}
      };
      rotateMatrix(N, mat);
      displayMatrix(N, mat);
   }
}

輸出

執行以上程式碼將生成以下輸出,

3 6 9 2 5 8 1 4 7

更新日期: 2021 年 2 月 5 日

2 千次瀏覽

啟動您的 職業

完成課程認證

開始
廣告