How do you rotate a two dimensional array?

后端 未结 30 3101
耶瑟儿~
耶瑟儿~ 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:18

    here is my In Place implementation in C

    void rotateRight(int matrix[][SIZE], int length) {
    
        int layer = 0;
    
        for (int layer = 0; layer < length / 2; ++layer) {
    
            int first = layer;
            int last = length - 1 - layer;
    
            for (int i = first; i < last; ++i) {
    
                int topline = matrix[first][i];
                int rightcol = matrix[i][last];
                int bottomline = matrix[last][length - layer - 1 - i];
                int leftcol = matrix[length - layer - 1 - i][first];
    
                matrix[first][i] = leftcol;
                matrix[i][last] = topline;
                matrix[last][length - layer - 1 - i] = rightcol;
                matrix[length - layer - 1 - i][first] = bottomline;
            }
        }
    }
    

提交回复
热议问题