2016-10-12 77 views
-1

有[x] [y]順序的矩陣。我想按順時針順序打印它的值please see the picture to make this clear.如何按順時針順序打印矩陣

我已經嘗試了幾種方法,但無法編寫代碼的邏輯。我在Java中嘗試它,但邏輯很重要,所以你可以用任何語言來幫助我。

+0

矩陣是正方形嗎? – Keiwan

+0

它可以..但不是必要的 –

+0

但如果你知道一個方陣的邏輯,那麼請分享 –

回答

0

當我閱讀你的文章時,我已經開始播放,所以我會發布你的代碼,也許它會對你有所幫助。如果你想要矩形,我需要單獨的stepX和stepY。 SIZE將是您的情況下的輸入參數,我有最後的靜態測試。

public class clockwise { 

    private static final int SIZE = 3; 

    public static void main(String[] args) { 
//  int[][] test_matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; 
     int[][] test_matrix = {{1,2,3},{5,6,7},{9,10,11}}; 
     int[][] direction = {{1, 0},{0, 1},{-1, 0},{0, -1}}; //{x,y} 

     for(int i = 0; i < SIZE; i++) { 
      for(int j = 0; j < SIZE; j++) 
       System.out.print(test_matrix[i][j] + " "); 
      System.out.println(""); 
     } 


     int x = 0; 
     int y = 0; 
     int directionMove = 0; 
     int stepSize = SIZE; 
     boolean changeStep = true; 
     int stepCounter = 0; 


     for(int i = 0; i < SIZE*SIZE; i++) { 
      System.out.print(test_matrix[x][y] + " "); 
      stepCounter++; 
      if (stepCounter % stepSize == 0) { 
       directionMove++; 
       directionMove = directionMove%4; 
       if(changeStep) { //after first edge one need to decrees step after passing two edges 
        stepSize--; 
        changeStep = false; 
       } else { 
        changeStep = true; 
       } 
       stepCounter = 0; 
      } 
      x += direction[directionMove][0]; 
      y += direction[directionMove][1]; 
     } 
    } 
}