2016-10-12 11 views
-1

[x] [y]の行列があります。私は時計回りにその値を表示したいplease see the picture to make this clear.行列を時計回りに印刷する方法

私はいくつかの方法を試みましたが、コードのロジックを書くことができませんでした。私はjavaで試していますが、ロジックは重要ですので、どの言語でも助けてください。

+0

行列は正方形ですか? – Keiwan

+0

でも可能ですが、必ずしも必要ではありません。 –

+0

ですが、正方行列のロジックを知っていれば、 –

答えて

0

あなたの投稿を読んだとき、私はあなたに私のコードを投稿してくれるようになったかもしれません。私は四角形のためにそれをやったことがあります。 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]; 
     } 
    } 
} 
関連する問題