實現矩陣的轉置較為容易,只需要將縱橫下標互換即可。實現矩陣旋轉稍微麻煩一點。
解題思路:
矩陣轉換90度,則原矩陣的縱下標轉變為新矩陣的橫下標;原矩陣的橫下標轉變為新矩陣的縱下標,并且順序相反。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class rotation { public static int [][] change( int [][]matrix){ int [][]temp= new int [matrix[ 0 ].length][matrix.length]; int dst=matrix.length- 1 ; for ( int i= 0 ;i<matrix.length;i++,dst--){ for ( int j= 0 ;j<matrix[ 0 ].length;j++){ temp[j][dst]=matrix[i][j]; } } return temp; } public static void main(string[]args){ int [][]matrix={{ 1 , 2 , 3 , 4 },{ 5 , 6 , 7 , 8 },{ 9 , 10 , 11 , 12 }}; int [][]temp=change(matrix); for ( int i= 0 ;i<temp.length;i++){ for ( int j= 0 ;j<temp[ 0 ].length;j++){ system.out.print(temp[i][j]+ "\t" ); } system.out.println(); } } } |
結果如下:
1
2
3
4
|
9 5 1 10 6 2 11 7 3 12 8 4 |
其實并不復雜,然而我在規定時間沒有編寫出來。。。果然還是需要多練習。
以上這篇java實現矩陣順時針旋轉90度的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/whuzhang16/article/details/77926341