2015-02-10 63 views
-1

我有一個二維數組在我的Java PRGM打印二維數組對角線從底部到頂部

[ 1 2 3 
    4 5 6 
    7 8 9 ] 

如何斜向順時針direction..such作爲

[ 9 8 6 
    7 5 3 
    4 2 1 ] 

本應安排此矩陣適用於爲了N.的所有方陣 任何人可以幫助我

class try2 
    { 
    public static void main (String[] args) throws java.lang.Exception 
    { 


int[][] elements = new int[][]{ 
      {1,5,9,13}, 
      {2,6,10,14}, 
      {3,7,11,15}, 
      {4,8,12,16} 
    }; 


    int i=0,j=0,k=0,l = 0; 
    int rows = 4,columns = 4; 
    // Elements to the left of secondary diagonal elements. 
    while(i<rows){ 

     k = i; 
     j=0; 
     // System.out.print("1 loop"); 
     //System.out.println(" "+k+""+j); 
     while(k>=0 && j>=0 && k<rows && j<columns){ 
      System.out.print(elements[k][j]+" "); 
      j++; 
      k--; 
     } 
     i++; 
     System.out.println(); 
    } 
    i = rows-1; 
    j = 1; 
    // elements to the right of secondary diagonal elements. 
    while(j<columns){ 
     k = i; 
     l = j; 
     //System.out.print("2 loop"); 
     //System.out.println(" "+k+""+l); 
     while(l<columns){ 
      System.out.print(elements[k][l]+" "); 
      l++; 
      k--; 
     } 
     System.out.println(); 
     j++; 
    } 
} 
} 

輸出I小號

1 
2 5 
3 6 9 
4 7 10 13 
8 11 14 
12 15 
16 

所需的輸出是

16 
12 15 
8 11 14 
4 7 10 13 
3 6 9 
2 5 
1 
+0

你只需要調試代碼,我相信沒有人會調試在這個論壇 – sashas 2015-02-10 14:38:10

回答

1

給你:

class Diag 
{ 
    public static void main(String[] args) throws java.lang.Exception 
    { 

     int[][] elements = new int[][] { 
       { 1, 5, 9, 13 }, 
       { 2, 6, 10, 14 }, 
       { 3, 7, 11, 15 }, 
       { 4, 8, 12, 16 } }; 

     int R = elements.length; 
     int C = elements[0].length; 

     for (int row = R - 1, col = C - 1; row >= 0 && col >= 0;) 
     { 
      if (col == C - 1 && row != 0) 
      { 
       System.out.println(elements[row][col]); 
       col = row - 1; 
       row = R - 1; 
       continue; 
      } 

      if (row == 0) 
      { 
       System.out.println(elements[row][col]); 
       row = col - 1; 
       col = 0; 
       continue; 
      } 

      System.out.print(elements[row][col] + " "); 
      row = (row - 1 + R) % R; 
      col = (col + 1) % C; 
     } 

    } 
} 
+0

代碼tanq soo much :-) – lpd 2015-02-10 15:19:05

+0

在你的行中=(row - 1 + R)%R;零件+ R)%R什麼都不做,因爲它是完全一樣的數字;) – omgBob 2015-02-10 15:31:27

+0

這是正確的,因爲在這一點上行不會等於零。這只是我通常添加的保護措施,以避免負面指數。 – restricteur 2015-02-10 15:46:13

0
class Solution { 
    public static void main(String[] args) { 

int a[][] = {{1, 2, 3, 4}, 
      {5, 6, 7, 8}, 
      {9, 10, 11, 12}}; 
int i=0,j=0; 
while(i<a[0].length){ 
    printDiagonal(0,i++,a,a[0].length,a.length); 
    if(i!=a[0].length-1) 
    System.out.println(); 
} 

i = 0; 
int len = a[0].length-1; 
while(i<a.length){ 
    printDiagonal(i++,len,a,a.length,a[0].length); 
    System.out.println(); 
} 
} 

public static void printDiagonal(int x, int y, int[][] A, int l1, int l2) { 
while(x >= 0 && y >= 0 && x < l1 && y < l2) 
    System.out.print(A[x++][y--] + " "); 
} 
}