How do you rotate a two dimensional array?

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

    Nick's answer would work for an NxM array too with only a small modification (as opposed to an NxN).

    string[,] orig = new string[n, m];
    string[,] rot = new string[m, n];
    
    ...
    
    for ( int i=0; i < n; i++ )
      for ( int j=0; j < m; j++ )
        rot[j, n - i - 1] = orig[i, j];
    

    One way to think about this is that you have moved the center of the axis (0,0) from the top left corner to the top right corner. You're simply transposing from one to the other.

提交回复
热议问题