题目链接:https://www.acwing.com/problem/content/description/39/
题目如下:
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { vector<int> result; if(matrix.size()==0) return result; int row=matrix.size(),col=matrix[0].size(); vector<vector<bool>> visited(row,vector<bool>(col,false));//是否已被访问标记矩阵 int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};//顺时针定义四个方向 int x=0,y=0,d=1;//从左上角开始遍历,先往右走,走到底,再更改到下个方向,走完n^2个格子为止 for(int i=0;i<row*col;i++){ result.push_back(matrix[x][y]); visited[x][y]=true; int a=x+dx[d],b=y+dy[d]; if(a<0||a>=row||b<0||b>=col||visited[a][b]==true){ d=(d+1)%4; a=x+dx[d],b=y+dy[d]; } x=a,y=b; } return result; } };