2011-10-20 72 views
1

可能重複:
Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)打印2- d陣列

如何打印在螺旋的次序使用JAVA 2維陣列?請幫忙,我沒有任何想法。

樣本陣列:

1 2 3 4 

5 6 7 8 

9 10 11 12 

13 14 15 16 

輸出:

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

這裏是我嘗試:

公共靜態無效的主要(字串[] args){

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

    for (int i = (values.length * values[0].length)-1, j = 0; i > 0; i--, j++) { 
      for (int k = j; k < i; k++) { 
       System.out.print(values[j][k]); 
      } 

      for (int k = j; k < i; k++) { 
       System.out.print(values[k][i]); 
      } 

      for (int k = i; k > j; k--) { 
       System.out.print(values[i][k]); 
      } 

      for (int k = i; k > j; k--) { 
       System.out.print(values[k][j]); 
      } 
    } 

} 
+2

相關:http://stackoverflow.com/questions/7042165/pattern-consisting-of-numbers-moving順時針方向 - 長方形 –

+2

這是作業嗎?你試過什麼了? –

回答

1

這裏是一些Java解決方案:

public static final int X_SIZE = 4; 
public static final int Y_SIZE = 4; 

public static void main(String[] args) { 
    int[][] array = new int[X_SIZE][Y_SIZE]; 

    for(int i = 0; i < X_SIZE; i++){ 
     for (int j = 0; j < Y_SIZE; j++){ 
      array[i][j] = i * X_SIZE + (j + 1); 
      System.out.print(array[i][j] + " "); 
     } 
     System.out.println(); 
    } 

    System.out.println("************"); 
    System.out.println("Spiral");  

    spiralPrint(X_SIZE, Y_SIZE, array); 
} 

public static void spiralPrint(int xSize, int ySize, int matrix[][]){ 
    int i, k = 0, l = 0; 
    xSize--; ySize--;  

    while(k <= xSize && l <= ySize){ 
     for(i = l; i <= ySize; ++i) { 
      System.out.print(matrix[k][i]+ " "); 
     }   
     k++; 

     for(i = k; i <= xSize; ++i) { 
      System.out.print(matrix[i][ySize] + " "); 
     } 
     ySize--; 

     for(i = ySize; i >= l; --i) { 
       System.out.print(matrix[xSize][i] + " "); 
     } 
     xSize--; 


     for(i = xSize; i >= k; --i) { 
      System.out.print(matrix[i][l] + " "); 
     } 
     l++; 
    } 
} 
+0

這是破碎的,只有矩陣寬度等於高度時纔有效 – aug70co

2
void PrintSpiral(int[][] arr, int size) 
{ 
    for (int l = 0; l < size/2; l++) 
    { 
     int min = l; 
     int max = size - 1 - l; 
     for (int i = min; i < max; i++) 
      System.out.print("\t" + arr[i][min].ToString()); 
     for (int j = min; j < max; j++) 
      System.out.print("\t" + arr[max][j].ToString()); 
     for (int i = max; i > min; i--) 
      System.out.print("\t" + arr[i][max].ToString()); 
     for (int j = max; j > min; j--) 
      System.out.print("\t" + arr[min][j].ToString()); 
    } 
    // centre is special case: avoiding printing it 4 times. 
    if (size % 2 == 1) 
     System.out.print("\t" + arr[size/2][size/2].ToString()); 
} 

(免責聲明:只在C#試過)