54. Spiral Matrix

来源:互联网 发布:矩阵谱分解 编辑:程序博客网 时间:2024/05/15 12:35

1. Description

Given a matrix of m*n elements, return all elements of the matrix in spiral order.


2. Solution

Just do it. In any loop, print the elements from left to right, top to down, right to left, and down to top.

Repeat the above process, until all elements have been printed.


3. Code

    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int>ans;        int n = matrix.size();        if(n==0) return ans;        int m = matrix[0].size();        int k=0,count = n*m;        int t=0,b=n-1,l=0,r=m-1;        while(k<count){            for(int i = l;i<=r&&k<count;i++){                ans.push_back(matrix[t][i]);                k++;            }            t++;            for(int i=t;i<=b&&k<count;i++){                ans.push_back(matrix[i][r]);                k++;            }            r--;            for(int i=r;i>=l&&k<count;i--){                ans.push_back(matrix[b][i]);                k++;            }            b--;            for(int i = b;i>=t&&k<count;i--){                ans.push_back(matrix[i][l]);                k++;                            }            l++;        }        return ans;    }


原创粉丝点击