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].
    

      注意几点: 1)spiral 总共转了几圈 2) 最后一圈的时候如果是“横”“竖”需要处理好边界

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
           vector<int> res;
            int rows = matrix.size();
            if(rows == 0) return res;
            int columns = matrix[0].size();
            if( columns ==0) return res;
    
            int lays = rows > columns ? (columns+1)/2 : (rows+1) /2; 
            bool single =  rows > columns ? columns%2 :rows%2 ;
            for(int lay = 0; lay < lays ; lay++)
            {
                int topRow = lay;
                int rightColumn = columns  - 1 - lay;
    
                //process the top row 
                for(int i = lay ; i <= rightColumn ; i++)
                    res.push_back(matrix[topRow][i]);
                //process the right column ,not include the first of the right column element 
                for(int i = lay +1 ; i <= rows - 1 - lay ; i++)
                    res.push_back(matrix[i][rightColumn]);
                
                if(lay == lays -1 && single)
                     continue ;
                //process the bottom row, not include the last of the bottom row element
                for(int i = rightColumn - 1 ;i >= lay ; i--)
                    res.push_back(matrix[rows-1-lay][i]);
    
                //process the left;
                for(int i = rows - 1 - lay -1  ;i > lay ; i--)
                    res.push_back(matrix[i][lay]);
    
            }
    
            return res;
        }
    };
  • 相关阅读:
    SQL Server2000的ROWGUID 列
    数据库主键设计之思考
    SQL Server 索引结构及其使用(四)
    一些基础表单的验证 函数
    JS加密编码算法
    textarea自动增高并隐藏滚动条
    HTML之打开/另存为/打印/刷新/查看原文件等按钮的代码
    Code Snippets
    jQuery验证框架
    Jquery 扩展验证
  • 原文地址:https://www.cnblogs.com/graph/p/3230130.html
Copyright © 2011-2022 走看看