zoukankan      html  css  js  c++  java
  • 21 Spiral Matrix

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

    Example 1:

    Input:
    [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    Example 2:

    Input:
    [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            
            vector<int> ans;
            
            if(matrix.empty()) return ans;
            
            int last_row = matrix.size() -1 ;
            int last_col = matrix[0].size() -1 ;
            
            int first_row = 0;
            int first_col = 0;
            
            while(first_row <= last_row && first_col <= last_col)
            {
                printEdges(matrix, ans, first_row,last_row, first_col, last_col);
                
            }
            
            
            return ans;
        }
        
        void printEdges(vector<vector<int>> matrix, vector<int>& ans, int& first_row, int& last_row, int& first_col,  int& last_col)
        {
            //print first row
            for(int i=first_col;i<=last_col; i++) ans.push_back(matrix[first_row][i]);
            
            //if
            if(last_row == first_row);
            else
            {
                //print last column
                for(int i=first_row+1;i<=last_row;i++) ans.push_back(matrix[i][last_col]);
                
                //print last row
                for(int i=last_col-1;i>=first_col;i--) ans.push_back(matrix[last_row][i]);
                
                 //if,print first column
                if(last_col == first_col);
                else
                {
                    for(int i=last_row-1;i>first_row;i--) ans.push_back(matrix[i][first_col]);
                
                }
                
                first_col++;
                last_row--;
                last_col--;
                   
            }
            
            //update pointer
            first_row++;
            
        }
        
    };
    
  • 相关阅读:
    websocket协议
    vue组件之间的传值
    vue中非父子组件的传值bus的使用
    $.proxy的使用
    弹性盒模型display:flex
    箭头函数与普通函数的区别
    粘贴到Excel的图片总是有些轻微变形
    centos rhel 中文输入法的安装
    vi ,默认为 .asm .inc 采用nasm的语法高亮
    how-to-convert-ppk-key-to-openssh-key-under-linux
  • 原文地址:https://www.cnblogs.com/xiaoyisun06/p/11395152.html
Copyright © 2011-2022 走看看