zoukankan      html  css  js  c++  java
  • [LeetCode] Spiral Matrix

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    For example, Given the following matrix:

    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    

    You should return [1,2,3,6,9,8,7,4,5].

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) {
            int m = matrix.size();//原矩阵m行n列
            vector<int> res;
            if(m==0)
                return res;
            int n = matrix[0].size();
            
            
            
            int rowStart=0,rowEnd=m-1,colStart=0,colEnd=n-1;
           
            int j=colStart,i=rowStart ;
            while(1)
            {
                
                for(j = colStart;j<=colEnd;j++)
                {
                    res.push_back(matrix[i][j]);
                }
                j = j-1;
                if(res.size()==m*n)
                    break;
                rowStart++;
                j = colEnd;
    
                for(i=rowStart;i<=rowEnd;i++)
                {
                    res.push_back(matrix[i][j]);
                }
                colEnd--;
                i = rowEnd;
                for(j=colEnd;j>=colStart;j--)
                {
                    res.push_back(matrix[i][j]);
    
                }
                j = j+1;
                if(res.size()==m*n)
                    break;
                rowEnd--;
                j=colStart;
                for(i = rowEnd;i>=rowStart;i--)
                {
                    res.push_back(matrix[i][j]);
                }
                colStart++;
                i = rowStart;
            }//end while
        return res;
        }
    };
  • 相关阅读:
    打开网页总结
    学期总结
    总结
    Sprint3
    Sprint2团队贡献分
    6.14
    典型用户与场景
    5种创建型模式
    JAVA 将接口的引用指向实现类的对象
    Java里的接口
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3870585.html
Copyright © 2011-2022 走看看