[英]Matrix not rotating 90 degree to Right
我想使用一維數組將矩陣向右旋轉 90 度,但它沒有給出所需的 output
我之前使用了一個簡單的方法,它確實有效,所以為了練習,我嘗試在單維數組的幫助下進行。
import java.util.Scanner;
public class nine
{
void main()
{
int M, i ,j;
int z=0;
int arr[][], x[];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ROW AND COLUMN OF MATRIX");
M=sc.nextInt();
arr=new int[M][M];
x=new int[M*M];
System.out.println("ENTER THE ELEMENTS IN MATRIX ");
for(i=0;i< M;i++)
{
for(j=0;j< M;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println( );
System.out.println( "------------------------------------------------------");
System.out.println("ORIGINAL MATRIX \n");
for(i=0;i< M;i++)
{
for(j=0;j< M;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println( );
System.out.println( "------------------------------------------------------");
/* giving matrix x the value of arr from bottom.
* example matrix-
1 2 3
4 5 6
7 8 9
value stored in x- {7 8 9 4 5 6 3 2 1}
*/
for(i=M-1;i>0;i--)
{
for(j=0;j< M;j++)
{
x[z]=arr[i][j];
z++;
}
}
z=0;
/*
* Adding values of matrix x in matrix arr veritcally.
*
*/
for(j=0;j< M;j++)
{
for(i=0;i< M;i++)
{
arr[i][j]= x[z];
z++;
}
}
/*
* Desired output from the example input-
* 7 4 1
8 5 2
9 6 3
*
*/
System.out.println("ROTATED MATRIX \n");
for(i=0;i< M;i++)
{
for(j=0;j< M;j++)
{
System.out.print(arr[i][j]+" " );
}
System.out.println( );
}
}
}
我想要的 output 是:
我得到的 output 是:
要旋轉,你需要這樣的東西:
int arr[][];
int dest[][];
arr = new int[M][M];
dest = new int[M][M];
for (int i=0; i<M, i++) {
for (int j=0; j<M, j++) {
dest[M-j-1][i] = arr[i][j];
}
}
此外,您倒計時循環需要包括零
for(i=M-1;i>0;i--)
應該
for(i=M-1;i>=0;i--)
(將 Ricky Mo 的評論變成一個改動和解釋最少的答案)
你很親密。 無需從根本上改變您的方法。
但是,您得到的 output 清楚地表明您的代碼沒有寫入最后一列。
一個明顯的結論是您的循環設置不正確。
確實(正如 Ricky Mo 簡潔地說的那樣):
將
for(i=M-1;i>0;i--)
更改for(i=M-1;i>=0;i--)
顯然它會更頻繁地迭代。
由於您正確實現了索引魔法,這最終出現在右側(即 0 值列)。
output 是:
ENTER THE NUMBER OF ROW AND COLUMN OF MATRIX
ENTER THE ELEMENTS IN MATRIX
------------------------------------------------------
ORIGINAL MATRIX
1 2 3
4 5 6
7 8 9
------------------------------------------------------
ROTATED MATRIX
7 4 1
8 5 2
9 6 3
例如這里:
https://www.tutorialspoint.com/compile_java_online.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.