地址 https://www.acwing.com/solution/acwing/content/3623/
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
算法1
顺时针 就是按照右 下 左 上 次序依次打印
并且建立同matrix同样大小的二维数组 记录该点是否已经访问 如果访问了则不能再进
在依次打印的过程中,如果遇到坐标不符合标准则右转90度,继续打印,直到一步都不能走了 则退出循环
C++ 代码
class Solution { public: vector<int> result; vector<vector<bool>> matrixFlag; int upd = 0; int downd = 1; int leftd = 2; int rightd = 3; int movex[4] = { -1,1,0,0 }; int movey[4] = { 0,0,-1,1 }; bool PrintInner(int& x, int& y, const vector<vector<int> >& matrix,int direct) { if (x < 0 || y < 0 || x >= matrix.size() || y >= matrix[0].size()) return false; if (matrixFlag[x][y] == false) return false; int xcopy = x; int ycopy = y; while (ycopy >= 0 && xcopy >= 0 && xcopy < matrix.size() && ycopy < matrix[0].size() && matrixFlag[xcopy][ycopy] == true) { result.push_back(matrix[xcopy][ycopy]); matrixFlag[xcopy][ycopy] = false; y = ycopy; x = xcopy; xcopy += movex[direct]; ycopy += movey[direct]; } return true; } vector<int> printMatrix(vector<vector<int> > matrix) { if (matrix.empty() || matrix[0].empty()) return result; int n = matrix.size(); int m = matrix[0].size(); matrixFlag = vector<vector<bool>>(n,vector<bool>(m,true)); int x = 0; int y = 0; while (1) { if (PrintInner(x, y, matrix, rightd) == false) break; x += movex[downd]; y += movey[downd]; if (PrintInner(x, y, matrix, downd) == false) break; x += movex[leftd]; y += movey[leftd]; if (PrintInner(x, y, matrix, leftd) == false) break; x += movex[upd]; y += movey[upd]; if (PrintInner(x, y, matrix, upd) == false) break; x += movex[rightd]; y += movey[rightd]; } return result; } }; 作者:defddr 链接:https://www.acwing.com/solution/acwing/content/3623/ 来源:AcWing 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。