2014-05-06 01:40
原题:
Give a N*N matrix, print it out diagonally. Follow up, if it is a M*N matrix, how to print it out. Example: 1 2 3 4 5 6 7 8 9 print: 1 2 4 3 5 7 6 8 9
题目:按照题目示例给出的方式,输出一个矩阵。
解法:按题意写代码即可。
代码:
1 // http://www.careercup.com/question?id=5661939564806144 2 #include <cstdio> 3 #include <vector> 4 using namespace std; 5 6 class Solution { 7 public: 8 void printDiagonal(vector<vector<int> > &matrix) { 9 int n, m; 10 11 n = (int)matrix.size(); 12 if (n == 0) { 13 return; 14 } 15 m = (int)matrix[0].size(); 16 if (m == 0) { 17 return; 18 } 19 20 int i, j; 21 bool first; 22 23 for (i = 0; i < n + m; ++i) { 24 first = true; 25 for (j = (i < m ? i : m - 1); j >= 0; --j) { 26 if (i - j < 0 || i - j > n - 1) { 27 break; 28 } 29 printf((first ? "%d" : " %d"), matrix[i - j][j]); 30 first = false; 31 } 32 printf(" "); 33 } 34 }; 35 };