2016-10-12 4 views
-1

[x] [y] 순서의 행렬이 있습니다. 시계 방향으로 값을 인쇄하고 싶습니다. please see the picture to make this clear.시계 방향으로 행렬을 인쇄하는 방법

나는 여러 가지 방법을 시도했지만 코드 논리를 작성할 수 없습니다. 나는 자바에서 그것을 시도하지만 로직은 중요하므로 모든 언어로 나를 도울 수 있습니다.

+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]; 
     } 
    } 
}