How do you rotate a two dimensional array?

后端 未结 30 3092
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  醉话见心
    2020-11-22 03:42

    This a better version of it in Java: I've made it for a matrix with a different width and height

    • h is here the height of the matrix after rotating
    • w is here the width of the matrix after rotating

     

    public int[][] rotateMatrixRight(int[][] matrix)
    {
        /* W and H are already swapped */
        int w = matrix.length;
        int h = matrix[0].length;
        int[][] ret = new int[h][w];
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                ret[i][j] = matrix[w - j - 1][i];
            }
        }
        return ret;
    }
    
    
    public int[][] rotateMatrixLeft(int[][] matrix)
    {
        /* W and H are already swapped */
        int w = matrix.length;
        int h = matrix[0].length;   
        int[][] ret = new int[h][w];
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                ret[i][j] = matrix[j][h - i - 1];
            }
        }
        return ret;
    }
    

    This code is based on Nick Berardi's post.

提交回复
热议问题