题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
思路:主要关注4个角,根据是哪个角,在做出相应的操作。
代码如下:
1 class Solution { 2 public: 3 vector<int> printMatrix(vector<vector<int> > matrix) { 4 vector<int> results; 5 if (matrix.size() == 0) { 6 return results; 7 } 8 9 int x = 0; 10 int y = 0; //当前元素的位置 11 12 int xf = 0; 13 int yf = 1;//xf和yf表示当前元素位置指针的方向,-1表后退,0停止,1前进 14 15 int rows = matrix.size()-1; //行 16 int cols = matrix.at(0).size()-1; //列 17 //当只有一行时 18 if (rows == 0) { 19 for (int i = 0; i <= cols; i++) { 20 results.push_back(matrix.at(0).at(i)); 21 } 22 return results; 23 } 24 //当只有一列时 25 if (cols == 0) { 26 for (int i = 0; i <= rows; i++) { 27 results.push_back(matrix.at(i).at(0)); 28 } 29 return results; 30 } 31 32 int x_start = 0; 33 int y_start = 0; 34 35 int x_end = rows; 36 int y_end = cols; 37 38 bool isFirst = true; 39 40 int size = (rows+1)*(cols+1); //元素个数 41 while (results.size() < size) { 42 results.push_back(matrix[x][y]); //记录当前元素 43 x += xf; //横坐标变换 44 y += yf; //纵坐标变化 45 //开始进行四个角的判断以及相关操作 46 if (x == x_start && y == y_end) { 47 xf = 1; 48 yf = 0; 49 if (!isFirst) { 50 y_start += 1; 51 } 52 } 53 if (x == x_end && y == y_end) { 54 xf = 0; 55 yf = -1; 56 y_end -= 1; 57 58 59 } 60 if (x == x_end && y == y_start) { 61 xf = -1; 62 yf = 0; 63 x_start += 1; 64 65 } 66 if (x == x_start && y == y_start) { 67 xf = 0; 68 yf = 1; 69 x_end -= 1; 70 isFirst = false; 71 } 72 } 73 return results; 74 } 75 };
时间: 2024-10-12 19:51:03