剑指offer 顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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个for循环遍历两行两列就行。而最终的终止条件很重要,我是直接利用矩阵元素个数作为终止条件。

 1 class Solution {
 2 public:
 3     vector<int> printMatrix(vector<vector<int> > matrix) {
 4         vector<int> v;
 5         int rows = matrix.size();
 6         if (rows == 0)
 7             return v;
 8         int columns = matrix[0].size();
 9         int cnt = 0; //用于记录打印出的数字个数,作为循环终止条件
10         int total = rows * columns;
11         int start_row = 0, start_col = 0, end_row = rows - 1, end_col = columns - 1;
12         while (cnt < total) {
13             //由于每个for循环都会改变cnt的值,这也直接影响后面for循环的执行,如果cnt到达
14             //终止条件,直接不执行,尤其可以解决单行单列的问题。
15             for (int j = start_col; cnt < total && j <= end_col; j++) {
16                 v.push_back(matrix[start_row][j]);
17                 cnt++;
18             }
19             for (int i = start_row + 1; cnt < total && i <= end_row; i++) {
20                 v.push_back(matrix[i][end_col]);
21                 cnt++;
22             }
23             for (int j = end_col - 1; cnt < total && j >= start_col; j--) {
24                 v.push_back(matrix[end_row][j]);
25                 cnt++;
26             }
27             for (int i = end_row - 1; cnt < total && i > start_row; i--) {
28                 v.push_back(matrix[i][start_col]);
29                 cnt++;
30             }
31             start_row++;
32             start_col++;
33             end_row--;
34             end_col--;
35         }
36         return v;
37     }
38 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/10636327.html