1. 程式人生 > >劍指Offer-順時針打印矩陣

劍指Offer-順時針打印矩陣

i++ 等於 代碼 return cto int color 數字 初始化

題目:

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路:

  首先確定矩陣的行數和列數,初始化4個變量:left = 0;right = col-1;top = 0;bottom = row-1。然後按照從左向後、從上向下、從右向左、從下向上的順序打印即可。需要註意的是,在打印從右向左時,需要判斷top是否等於bottom;若相等,則不必打印該行;在打印從下向上時,需要判斷left是否等於right,若相等,則不必打印該列。

代碼:

技術分享
 1 class Solution {
 2 public:
 3     vector<int> printMatrix(vector<vector<int> > matrix) {
 4         int bottom = matrix.size() - 1;
 5         int right = matrix[0].size() - 1;
 6         int left = 0;
 7         int top = 0;
 8         vector<int> result;
 9         while
(left <= right && top <= bottom) { 10 //從左向右 11 for (int i = left; i <= right; i++) 12 result.push_back(matrix[top][i]); 13 //從上向下 14 for (int i = top + 1; i <= bottom; i++) 15 result.push_back(matrix[i][right]);
16 if (top != bottom) 17 //從右向左 18 for (int i = right - 1; i >= left; i--) 19 result.push_back(matrix[bottom][i]); 20 if (left != right) 21 //從下向上 22 for (int i = bottom - 1; i >= top + 1; i--) 23 result.push_back(matrix[i][left]); 24 left++; 25 right--; 26 top++; 27 bottom--; 28 } 29 return result; 30 } 31 };
View Code

劍指Offer-順時針打印矩陣