剑指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.

思路:用方向数组按规则遍历所有点,每个点被访问过之后,就进行标记。
#include <iostream>
#include <vector>
using namespace std;

class Solution {
    
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        
        vector<vector<int>> vis(row, vector<int>(col, 0));
        
        int step_x[4] = {0,1,0,-1}, step_y[4] = {1,0,-1,0};
        
        int flag = 0;
        
        vector<int> res;
        res.push_back(matrix[0][0]);
        int i=0,j=0;
        vis[i][j] = 1;
        
        while(1)
        {
            if(res.size() == row*col)
                break;
            i += step_x[flag%4], j += step_y[flag%4];
        
            if(i>=0 && j >=0 && i < row && j < col && vis[i][j] == 0)
            {
                res.push_back(matrix[i][j]);
                vis[i][j] = 1;
            }
            else
            {
                i -= step_x[flag%4], j -= step_y[flag%4];
                flag++;
            }
        }
        return res;
    }
};


int main() {
    // insert code here...
    Solution sol;
    vector<vector<int>> matrix ={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    vector<int> res = sol.printMatrix(matrix);
    for(auto i:res)
        cout << i << endl;
    return 0;
}
View Code

 

posted @ 2019-06-28 21:52  unicoe  阅读(176)  评论(0编辑  收藏  举报