如何以顺时针顺序打印矩阵

时间:2016-10-12 17:51:44

标签: java matrix puzzle

[x] [y]顺序有矩阵。我想以顺时针顺序please see the picture to make this clear.

打印其值

我尝试了几种方法但无法编写代码的逻辑。我在java中尝试它但逻辑非常重要,所以你可以用任何语言帮助我。

1 个答案:

答案 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];
        }   
    }
}