2017-03-21 67 views
0

我試圖在2D陣列(具體的方矩陣),使得結果是一個「階梯」圖案轉移元件的權利:爪哇:遞增地移動在一個二維數組元素

原件:

1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25 

目的:

1 2 3 4 5 
10 6 7 8 9 
14 15 11 12 13 
18 19 20 16 17 
22 23 24 25 21 

我已經成功地寫入,可以在一維數組執行該任務的矩陣的第一行的程序(見下文),但我似乎無法翻譯代碼,以便它在2D數組中運行。

  • 如何讓我的代碼在Java中的二維數組中運行?
  • 而且,以後我該如何增加變化,以便隨着行增加(從矩陣的上層到下層),輪班次數也增加了?

public class StaircaseMatrix 
 
{ 
 
    public static void main(String[] args) 
 
    { 
 
     int[] num = {1,2,3,4,5}; 
 

 
     shiftRight(num); 
 

 
     System.out.println("After shifting the array is:"); 
 
     for (int x = 0; x < num.length; x++) 
 
      System.out.print(num[x] + " "); 
 
    } 
 

 

 
    public static void shiftRight(int[] list) 
 
    { 
 
     int last = list[list.length - 1]; 
 
     for (int j = list.length - 1; j > 0; j--) { 
 
      list[j] = list[j - 1]; 
 
     } 
 
     list[0] = last; 
 
    } 
 
}

回答

0

您致電array2D[0]shiftRight() 0次,1次爲array2D[1],2次爲array2D[2],等等,使用for循環。