《Cracking the Coding Interview》——第1章:数组和字符串——题目6

2014-03-18 01:45

题目:给定一个NxN的矩阵,就地旋转90度。(没有样例又不说方向的话,随便往哪儿转。)

解法:如果N为奇数,除了中心点以外四等分。如果N为偶数,四等分。按照A->B->C->D->A的方式,轮换赋值,需要O(1)的额外空间保存A的值。

代码:

 1 // 1.6 Given an image represented by an NXN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

 2 #include <cstdio>

 3 #include <vector>

 4 using namespace std;

 5 

 6 class Solution {

 7 public:

 8     void rotateImage90(vector<vector<int> > &board) {

 9         int n = (int)board.size();

10         int i, j;

11         

12         if (n < 2) {

13             return;

14         }

15         int w, h;

16         int tmp;

17         

18         w = n / 2;

19         h = n - w;

20         for (i  = 0; i < w; ++i) {

21             for (j = 0; j < h; ++j) {

22                 tmp = board[i][j];

23                 board[i][j] = board[n - 1 - j][i];

24                 board[n - 1 - j][i] = board[n - 1 - i][n - 1 - j];

25                 board[n - 1 - i][n - 1 - j] = board[j][n - 1 - i];

26                 board[j][n - 1 - i] = tmp;

27             }

28         }

29     }

30 };

31 

32 int main()

33 {

34     vector<vector<int> > board;

35     int i, j, n;

36     Solution sol;

37     

38     while (scanf("%d", &n) == 1 && n > 0) {

39         board.resize(n);

40         for (i = 0; i < n; ++i) {

41             board[i].resize(n);

42         }

43         

44         for (i = 0; i < n; ++i) {

45             for (j = 0; j < n; ++j) {

46                 scanf("%d", &board[i][j]);

47             }

48         }

49         sol.rotateImage90(board);

50         for (i = 0; i < n; ++i) {

51             printf("%d", board[i][0]);

52             for (j = 1; j < n; ++j) {

53                 printf(" %d", board[i][j]);

54             }

55             printf("\n");

56         }

57         printf("\n");

58         

59         for (i = 0; i < n; ++i) {

60             board[i].clear();

61         }

62         board.clear();

63     }

64     

65     return 0;

66 }

 

你可能感兴趣的:(interview)