C++/代码:

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> res; //定义一维数组
        int m = matrix.size(), n = matrix[0].size(); //定义行为m,列为n
        vector<vector<bool>> st(m,vector<bool>(n,false)); //定义一个二维bool型数组,判定是否数组访问过
        int dx[4]={0,1,0,-1}, dy[4]={1,0,-1,0}; //定义上左下右
        int x = 0, y = 0 ,d = 0; //从(0,0)开始遍历,d = 0表示先从右边开始
        for (int i = 0; i < n * m; i ++) { //访问n*m次
            res.push_back(matrix[x][y]); //将访问的数保存至res一维数组
            st[x][y] = true; //将访问的数定义为false
            int a = x + dx[d], b= y + dy[d];
            if (a < 0 || a >= m || b < 0 || b >= n || st[a][b] ) {
                d = (d + 1) % 4;
                a = x + dx[d], b = y + dy[d];
            }
            x = a, y = b;
        }
        return res;
    }
};