How do you rotate a two dimensional array?

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

    Here is one that does the rotation in place instead of using a completely new array to hold the result. I've left off initialization of the array and printing it out. This only works for square arrays but they can be of any size. Memory overhead is equal to the size of one element of the array so you can do the rotation of as large an array as you want.

    int a[4][4];
    int n = 4;
    int tmp;
    for (int i = 0; i < n / 2; i++)
    {
        for (int j = i; j < n - i - 1; j++)
        {
            tmp             = a[i][j];
            a[i][j]         = a[j][n-i-1];
            a[j][n-i-1]     = a[n-i-1][n-j-1];
            a[n-i-1][n-j-1] = a[n-j-1][i];
            a[n-j-1][i]     = tmp;
        }
    }
    

提交回复
热议问题